Compare commits

...

63 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
192 changed files with 174472 additions and 318 deletions

View File

@@ -6,9 +6,10 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
- Main orchestration: `ansible/site.yml`
- Inventory and layering inputs: `ansible/inventory/hosts.yml`, `ansible/inventory/group_vars/*.yml`, `ansible/inventory/host_vars/*.yml`
- 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.
- OpenCode loads its entrypoint configuration from `dotfiles/common/.config/opencode/opencode.json`.
- 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`; 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`.
- 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
- 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
with explicit authorization; retain only the ongoing desired-state configuration and
historical documentation, not permanent cleanup flags or tasks.
- Use Git Flow branch prefixes: `feature/` for new functionality, `bugfix/` for non-urgent fixes,
`hotfix/` for urgent production fixes, `release/` for release preparation, and `support/` for
maintained release lines. Do not use abbreviated prefixes such as `feat/`.
- Use trunk-based development: `main` is the single long-lived branch. Land small,
validated changes quickly, either as direct commits or via short-lived branches merged
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.
- 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.
@@ -56,7 +58,9 @@ Ansible-driven personal infrastructure repo for Fedora and Void desktops, Fedora
- 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`
- 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`
- 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.
- 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`
@@ -101,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.
- 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.
- 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`.
- Use `no_log: true` for secret-bearing task inputs or outputs.
@@ -116,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)
- 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.
- `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.
- `nymph` is the Fedora/GNOME laptop target; keep GNOME settings unmanaged for now and add host-specific tuning only after real use.
@@ -134,7 +141,6 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
## Workstation Notes
- `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 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.
## Rocky Server Notes
@@ -224,6 +230,19 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
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
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
@@ -545,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`.
- 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.
- 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.
- 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.
- 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
- Install local tooling with:
@@ -581,3 +604,16 @@ validated exports of older historical data will use a dedicated Atlas NFS datase
not depend on the AdGuard container during startup.
- 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.
## 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 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
- preparazione di Fedora WSL con `systemd` per il toolchain di sviluppo
- 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 |
| --- | --- | --- |
| `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 |
| `backend_phase1` | Quadlet rootless Navidrome e Syncthing | 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_*`.
The official ChatGPT desktop RPM is enabled only on `ikaros` and `nymph`. The
playbook configures OpenAI's signed RPM repository and imports its pinned RPM
signing key before installation; subsequent updates are handled by DNF.
The official ChatGPT desktop RPM is installed only on `ikaros` and `nymph`
through their `chatgpt_desktop_install_enabled` host overrides. The playbook
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
@@ -114,7 +116,7 @@ The workstation receives two layers:
- Fedora development setup through `workstation_dev_fedora`.
- 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
@@ -575,8 +577,8 @@ ansible-playbook ansible/site.yml --limit <host> --tags emacs -e emacs_enabled=t
## AI coding agents
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
only on `ikaros`. Each agent has its own lifecycle flags in
GitHub Copilot; IBM Bob is also managed on Fedora workstations. Codex Relay is installed
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,
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
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:
```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
```
### 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
| Role | What it does |
@@ -769,3 +893,13 @@ For a future Void desktop host:
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.
## 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.
# Installation and removal are mutually exclusive per agent; the common
# 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_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:
opencode:
npm_package: opencode-ai
install_enabled: true
deploy_enabled: true
uninstall_enabled: false
claude_code:
npm_package: "@anthropic-ai/claude-code"
install_enabled: "{{ opencode_install_enabled }}"
deploy_enabled: "{{ opencode_deploy_enabled }}"
uninstall_enabled: "{{ opencode_uninstall_enabled }}"
opencode_mobile:
npm_package: opencode-mobile
install_enabled: false
deploy_enabled: false
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:
npm_package: "@openai/codex"
install_enabled: true
deploy_enabled: true
uninstall_enabled: false
install_enabled: "{{ codex_install_enabled }}"
deploy_enabled: "{{ codex_deploy_enabled }}"
uninstall_enabled: "{{ codex_uninstall_enabled }}"
codex_relay:
npm_package: codex-relay
install_enabled: "{{ codex_relay_install_enabled }}"
deploy_enabled: false
uninstall_enabled: false
uninstall_enabled: "{{ codex_relay_uninstall_enabled }}"
gemini_cli:
npm_package: "@google/gemini-cli"
install_enabled: true
deploy_enabled: true
uninstall_enabled: false
install_enabled: "{{ gemini_cli_install_enabled }}"
deploy_enabled: "{{ gemini_cli_deploy_enabled }}"
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:
npm_package: "@github/copilot"
install_enabled: false
deploy_enabled: false
uninstall_enabled: true
ibm_bob:
install_enabled: true
install_enabled: "{{ ibm_bob_install_enabled }}"
deploy_enabled: false
uninstall_enabled: false
uninstall_enabled: "{{ ibm_bob_uninstall_enabled }}"
ai_agents_deploy_enabled_names: >-
{{ ai_agents | dict2items | selectattr('value.deploy_enabled') | map(attribute='key') | list }}
@@ -143,6 +175,7 @@ ai_agents_dotfiles:
- opencode
- codex
- gemini_cli
- cline
- name: Gemini CLI config
src: .gemini/
dest: .gemini/
@@ -161,6 +194,24 @@ ai_agents_dotfiles:
mode: preserve
agents:
- 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:
- name: Codex config

View File

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

View File

@@ -4,6 +4,9 @@ desktop_environment: gnome
desktop_sessions_enabled: []
desktop_default_session: gnome
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
# workstation_* so nymph can remain a desktop laptop rather than a dev workstation.
@@ -22,7 +25,7 @@ fedora_desktop_packages:
- croc
- delve
- dnsmasq
- evolution
- thunderbird
- fastfetch
- poppler-glib
- poppler-utils
@@ -73,6 +76,10 @@ fedora_desktop_packages:
- yt-dlp
- zstd
fedora_removed_packages:
- evolution
- evolution-langpacks
fedora_nerd_fonts_version: v3.3.0
fedora_nerd_fonts:
- Hack
@@ -83,7 +90,82 @@ fedora_nerd_fonts:
fedora_flatpak_packages:
- be.alexandervanhee.gradia
- ch.protonmail.protonmail-bridge
- com.spotify.Client
- org.desktop_plus.desktop-plus
- org.onlyoffice.desktopeditors
- 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
- jq
- 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
- ripgrep
@@ -60,10 +63,54 @@ fedora_dev_packages:
fedora_flatpak_remote_name: flathub
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:
- "43"
- "44"
- "45"
chatgpt_desktop_supported_architectures:
- x86_64
- aarch64

View File

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

View File

@@ -1,6 +1,12 @@
---
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:
- path: "{{ user_home }}/.config"
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:
- docker
@@ -7,26 +11,17 @@ workstation_dev_wsl_packages:
- helm
# Fedora ships the kubectl client binary in the kubernetes-client package.
- kubernetes-client
- mise
- pinentry-curses
- python3-pip
- tmux
# Java 11, Java 25 and Maven are managed by Mise on this Fedora WSL profile.
# Keep their versions pinned; update them deliberately.
workstation_mise_java_version: temurin-11.0.31+11
workstation_mise_java_25_version: 25.0.2
workstation_mise_maven_version: 3.9.16
# Maven version pinned in the devcontainer images; update it deliberately.
workstation_maven_version: 3.9.16
workstation_cdp_node_version: 20.18.3
workstation_is_wsl: true
workstation_wsl_systemd_enabled: true
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
dest: .gnupg/gpg-agent.conf
mode: "0600"

View File

@@ -72,7 +72,9 @@ atlas_nextcloud_external_mounts:
source: /zpool/archive/Documents
target: /mnt/archive-documents
readonly: false
- name: Foto iCloud
# 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
@@ -95,6 +97,17 @@ atlas_nextcloud_apps:
url: https://github.com/nextcloud-releases/calendar/releases/download/v6.6.2/calendar-v6.6.2.tar.gz
checksum: sha256:7e83632d4436d3037a34d1c73cbc06d5ccb6e8fc10f096a86a43a0515588529c
# 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_gitea_production_enabled: true
atlas_gitea_public_domain: git.fscotto.co

View File

@@ -1,6 +1,30 @@
---
hostname: deadalus
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_enabled_services: []

View File

@@ -1,10 +1,20 @@
---
hostname: ikaros
codex_relay_install_enabled: true
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
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:
- podman
- openssh-clients
- openssh-server
- mesa-vulkan-drivers
@@ -141,7 +151,7 @@ gnome_gsettings_settings:
value: "'file:///usr/share/backgrounds/gnome/morphogenesis-l.svg'"
- schema: org.gnome.desktop.search-providers
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
key: switch-to-workspace-1
value: "['<Super>1']"
@@ -204,7 +214,7 @@ gnome_gsettings_settings:
value: "false"
- schema: org.gnome.nautilus.preferences
key: default-folder-viewer
value: "'list-view'"
value: "'icon-view'"
- schema: org.gnome.nautilus.preferences
key: show-create-link
value: "true"
@@ -232,19 +242,19 @@ gnome_gsettings_settings:
- schema: org.gnome.shell
key: app-picker-layout
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
key: disabled-extensions
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
key: enabled-extensions
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
key: favorite-apps
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
key: remember-mount-password
value: "true"

View File

@@ -1,7 +1,13 @@
---
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
# 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:
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
tags: [dotfiles, dotfiles:common, ai_agents]
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"
- 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
tags: [packages, heic]
ansible.builtin.dnf:
@@ -66,12 +52,16 @@
ansible.builtin.dnf:
update_cache: true
- name: Install HEIC decoder on Fedora desktops
- name: Install HEIC decoder when RPM Fusion has a compatible build
tags: [packages, heic]
ansible.builtin.dnf:
name: libheif-freeworld
state: present
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"
- name: Install packages on Fedora
@@ -140,6 +130,10 @@
name: "{{ item.value.npm_package }}"
global: true
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 }}"
when:
- item.value.install_enabled | bool
@@ -160,55 +154,29 @@
loop_control:
label: "{{ item.key }}"
- name: Validate ChatGPT desktop architecture on Fedora
- name: Manage ChatGPT desktop lifecycle on Fedora graphical hosts
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_enabled | bool
ansible.builtin.import_tasks: chatgpt_desktop.yml
when:
- "'graphical_desktop' in group_names"
- chatgpt_desktop_install_enabled | default(false) | bool
or chatgpt_desktop_uninstall_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_enabled | bool
- name: Manage OpenCode Desktop lifecycle on Fedora graphical hosts
tags: [packages, opencode_desktop]
ansible.builtin.import_tasks: opencode_desktop.yml
when:
- "'graphical_desktop' in group_names"
- opencode_desktop_install_enabled | default(false) | bool
or opencode_desktop_uninstall_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_enabled | 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: Manage Cline Desktop lifecycle on Fedora graphical hosts
tags: [packages, cline_desktop]
ansible.builtin.import_tasks: cline_desktop.yml
when:
- "'graphical_desktop' in group_names"
- cline_desktop_install_enabled | default(false) | bool
or cline_desktop_uninstall_enabled | default(false) | bool
- name: Define Fedora Flatpak applications
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
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
tags: [packages, display-manager]
ansible.builtin.stat:

View File

@@ -18,6 +18,11 @@ atlas_nextcloud_redis_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_users: []
atlas_nextcloud_apps: []
@@ -325,3 +330,30 @@ 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

@@ -26,6 +26,9 @@
- name: Import Atlas iCloudPD storage and boot-started Quadlet tasks
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

View File

@@ -3,11 +3,14 @@
tags: [atlas, nextcloud_backup]
when: atlas_manage_nextcloud | bool
block:
- name: Validate private backup scope and local bundle retention
- 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

View File

@@ -74,6 +74,18 @@
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 }}"

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

@@ -14,6 +14,9 @@ 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

View File

@@ -7,6 +7,7 @@ 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 }}
@@ -64,6 +65,36 @@ recover() {
}
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 ]]

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

@@ -562,6 +562,10 @@
name: "{{ item.value.npm_package }}"
global: true
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 }}"
when:
- 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 }}"
group: "{{ user_group }}"
mode: "{{ item.mode }}"
loop: "{{ desktop_common_dotfiles | default([]) }}"
loop: "{{ (desktop_common_dotfiles | default([])) + (desktop_gnome_dotfiles | default([])) }}"
loop_control:
label: "{{ item.dest }}"
@@ -279,3 +279,17 @@
loop_control:
label: "{{ item }}"
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
state: latest
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 }}"
when:
- 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
tags: [dotfiles, dotfiles:workstation, emacs, wsl]
ansible.builtin.file:
@@ -55,51 +65,6 @@
loop_control:
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
tags: [packages, services]
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:
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:
- role: dotfiles_common
when:
@@ -122,6 +135,9 @@
roles:
- profile_desktop_gnome
- role: desktop_ai_media
when: desktop_ai_media_enabled | default(false) | bool
tags: [ai_media]
- name: Configure Fedora workstation development layer
hosts: workstation_dev_fedora
@@ -136,3 +152,12 @@
roles:
- 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]
defaultBranch = main
[core]
excludesfile = ~/.gitignore_global
excludesfile = {{ git_support_dir }}/.gitignore_global
pager = delta
[user]
@@ -24,11 +26,21 @@
[merge]
conflictstyle = diff3
tool = bobide
tool = {{ 'vscode' if in_container else 'bobide' }}
[mergetool]
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"]
cmd = bobide --reuse-window --wait $MERGED
@@ -37,6 +49,7 @@
[difftool "bobide"]
cmd = bobide --reuse-window --wait --diff $LOCAL $REMOTE
{% endif %}
[color]
ui = always
@@ -79,7 +92,7 @@
gcunreachablenow = gc --prune=now
[include]
path = ~/.themes.gitignore
path = {{ git_support_dir }}/.themes.gitignore
[delta]
features = catppuccin-mocha navigate
@@ -88,14 +101,16 @@
tabs = 4
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
sslCAInfo = ~/.local/share/certs/ecaas.datacenter.comune.roma.crt
[http "https://gitlab.datacenter.comune.roma"]
sslBackend = openssl
sslCAInfo = ~/.local/share/certs/datacenter.comune.roma.crt
{% endif %}
sslCAInfo = {{ '/run/ecaas-git-ca' if in_container else '~/.local/share/certs' }}/{{ ca.certificate }}
{% endfor %}
{% if not in_container %}
[credential]
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

3
cmd/devcontainer/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/fscotto/infra/cmd/devcontainer
go 1.22

351
cmd/devcontainer/main.go Normal file
View File

@@ -0,0 +1,351 @@
// Command devcontainer generates project configurations sharing host Git and agent state.
package main
import (
"bytes"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"sort"
"strings"
)
//go:embed delta.Dockerfile
var deltaDockerfile string
type profile struct {
Image, Packages string
Extensions []string
}
type agent struct {
Package string
Extension string
Paths []string
}
type mount struct {
Type string `json:"type"`
Source string `json:"source"`
Target string `json:"target"`
ReadOnly bool `json:"readOnly"`
}
func exists(path string) bool { _, err := os.Stat(path); return err == nil }
func isDir(path string) bool { info, err := os.Stat(path); return err == nil && info.IsDir() }
func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" }
func symlink(path string) bool {
info, err := os.Lstat(path)
return err == nil && info.Mode()&os.ModeSymlink != 0
}
func selectAgents(selection, home string) ([]string, error) {
result := []string{}
candidates := strings.Split(selection, ",")
if selection == "none" {
return result, nil
}
if selection == "auto" {
candidates = nil
for name := range agents {
candidates = append(candidates, name)
}
sort.Strings(candidates)
}
seen := map[string]bool{}
for _, name := range candidates {
name = strings.TrimSpace(name)
a, ok := agents[name]
if !ok {
return nil, fmt.Errorf("unknown agent %q", name)
}
available := true
for _, path := range a.Paths {
if !isDir(filepath.Join(home, path)) {
available = false
}
}
if selection == "auto" && !available {
continue
}
if !seen[name] {
result = append(result, name)
seen[name] = true
}
}
return result, nil
}
func generate(project, language, home string, selected []string, local []string, force bool) (string, error) {
p, ok := profiles[language]
if !ok {
return "", fmt.Errorf("unknown language %q", language)
}
project, err := filepath.Abs(project)
if err != nil {
return "", err
}
project, err = filepath.EvalSymlinks(project)
if err != nil {
return "", err
}
home, err = filepath.Abs(home)
if err != nil {
return "", err
}
home, err = filepath.EvalSymlinks(home)
if err != nil {
return "", err
}
if !isDir(project) {
return "", fmt.Errorf("project directory does not exist: %s", project)
}
if home == "/" || strings.ContainsAny(home, "\n\r$,\\\"") {
return "", errors.New("unsupported host home path")
}
target := filepath.Join(project, ".devcontainer")
if symlink(target) {
return "", errors.New("refusing a symlinked .devcontainer directory")
}
if exists(target) && !force {
return "", errors.New(".devcontainer already exists; use --force to replace generated files")
}
paths := []struct {
path string
readonly bool
}{{".gitconfig", true}, {".config/git", true}, {".gitignore_global", true}, {".config/ai", true}}
claude := false
for _, name := range selected {
a, ok := agents[name]
if !ok {
return "", fmt.Errorf("unknown agent %q", name)
}
for _, path := range a.Paths {
if !isDir(filepath.Join(home, path)) {
return "", fmt.Errorf("missing host directory for %s: %s", name, filepath.Join(home, path))
}
paths = append(paths, struct {
path string
readonly bool
}{path, false})
}
if name == "claude" {
claude = true
}
}
if claude {
paths = append(paths, struct {
path string
readonly bool
}{".claude.json", false})
}
mounts := []mount{}
for _, item := range paths {
if exists(filepath.Join(home, item.path)) {
destination := filepath.Join(home, item.path)
if item.path == ".gitconfig" {
destination = "/run/host-gitconfig"
}
mounts = append(mounts, mount{"bind", "${localEnv:HOME}/" + item.path, destination, item.readonly})
}
}
// The devcontainers node feature ships an nvm-based Node outside sudo's
// secure_path, which broke the postCreateCommand npm install. Copy the
// official Node image binaries into /usr/local instead, exactly like the
// ecaas and cdp devcontainers, so sudo npm works in every profile.
needsNode := len(selected) > 0
dockerfile := ""
if needsNode {
dockerfile += "FROM docker.io/library/node:22-bookworm-slim AS node\n"
}
dockerfile += fmt.Sprintf("FROM %s\nUSER root\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client ripgrep zoxide %s \\\n && rm -rf /var/lib/apt/lists/*\n", p.Image, p.Packages)
if needsNode {
dockerfile += "COPY --from=node /usr/local/bin/node /usr/local/bin/node\n"
dockerfile += "COPY --from=node /usr/local/lib/node_modules/npm/ /usr/local/lib/node_modules/npm/\n"
dockerfile += "RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \\\n && ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \\\n && node --version && npm --version\n"
}
dockerfile += deltaDockerfile
if home != "/home/vscode" {
dockerfile += "RUN usermod --home " + quote(home) + " --move-home vscode\n"
}
// Docker ENV uses its own quoting syntax, rather than shell quoting.
envHome, _ := json.Marshal(home)
dockerfile += "ENV HOME=" + string(envHome) + "\n"
if language == "python" {
dockerfile += "RUN python -m pip install --no-cache-dir uv ruff ty\n"
}
if language == "infra" {
dockerfile += "RUN python -m pip install --no-cache-dir ansible-core ansible-lint yamllint\n"
}
// The container installs the profile extensions, the VS Code extension of
// every selected agent and the extensions currently installed in the local
// VS Code, captured at generation time. Regenerate to refresh the local set.
extensions := append([]string{}, p.Extensions...)
addExtension := func(id string) {
if !slices.ContainsFunc(extensions, func(e string) bool { return strings.EqualFold(e, id) }) {
extensions = append(extensions, id)
}
}
for _, name := range selected {
if id := agents[name].Extension; id != "" {
addExtension(id)
}
}
for _, id := range local {
addExtension(strings.TrimSpace(id))
}
slices.Sort(extensions)
config := map[string]any{
"name": filepath.Base(project) + " — " + language,
"build": map[string]string{"dockerfile": "Dockerfile"},
"remoteUser": "vscode", "updateRemoteUserUID": true,
"containerEnv": map[string]string{"HOME": home}, "mounts": mounts,
"customizations": map[string]any{"vscode": map[string]any{"extensions": extensions}},
}
if len(selected) > 0 {
packages := []string{}
for _, name := range selected {
packages = append(packages, quote(agents[name].Package))
}
config["postCreateCommand"] = "sudo npm install --global --no-audit --no-fund " + strings.Join(packages, " ")
}
if claude {
config["remoteEnv"] = map[string]string{"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"}
}
dockerfile += "USER vscode\n"
if exists(filepath.Join(home, ".gitconfig")) {
dockerfile += "RUN git config --global include.path /run/host-gitconfig\n"
}
var data bytes.Buffer
encoder := json.NewEncoder(&data)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
if err := encoder.Encode(config); err != nil {
return "", err
}
files := []struct{ name, content string }{{"Dockerfile", dockerfile}, {"devcontainer.json", data.String()}}
// Validate every output before replacing any file.
for _, file := range files {
path := filepath.Join(target, file.name)
if info, err := os.Lstat(path); err == nil {
if !info.Mode().IsRegular() {
return "", fmt.Errorf("refusing non-regular output: %s", path)
}
} else if !os.IsNotExist(err) {
return "", err
}
}
if err := os.MkdirAll(target, 0755); err != nil {
return "", err
}
for _, file := range files {
if err := writeAtomic(filepath.Join(target, file.name), file.content); err != nil {
return "", err
}
}
return target, nil
}
func writeAtomic(path, content string) error {
file, err := os.CreateTemp(filepath.Dir(path), ".devcontainer-*")
if err != nil {
return err
}
defer os.Remove(file.Name())
if _, err = io.WriteString(file, content); err != nil {
file.Close()
return err
}
if err = file.Chmod(0644); err != nil {
file.Close()
return err
}
if err = file.Close(); err != nil {
return err
}
return os.Rename(file.Name(), path)
}
// discoverLocalExtensions lists the extensions installed in the local VS Code.
// A missing or failing code binary is not fatal: the generated container then
// only carries the profile and agent extensions.
func discoverLocalExtensions(stderr io.Writer) []string {
path, err := exec.LookPath("code")
if err != nil {
fmt.Fprintln(stderr, "note: no local VS Code found; skipping locally installed extensions")
return nil
}
out, err := exec.Command(path, "--list-extensions").Output()
if err != nil {
fmt.Fprintf(stderr, "warning: could not list local VS Code extensions: %v\n", err)
return nil
}
extensions := []string{}
for _, line := range strings.Split(string(out), "\n") {
if id := strings.TrimSpace(line); id != "" {
extensions = append(extensions, id)
}
}
return extensions
}
func run(args []string, home string, out, stderr io.Writer) error {
flags := flag.NewFlagSet("devcontainer", flag.ContinueOnError)
flags.SetOutput(stderr)
language := flags.String("language", "", "c-cpp, go, rust, python, node, java, infra (required)")
selection := flags.String("agents", "auto", "auto, none, or comma-separated codex,cline,opencode,claude,gemini")
force := flags.Bool("force", false, "Replace the two generated files")
flags.Usage = func() {
fmt.Fprintln(stderr, "Usage: devcontainer PROJECT --language LANGUAGE [--agents AGENTS] [--force]")
flags.PrintDefaults()
}
// Accept the project's original position before the flags as well as flags first.
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
args = append(append([]string{}, args[1:]...), args[0])
}
if err := flags.Parse(args); err != nil {
return err
}
if flags.NArg() != 1 || *language == "" {
flags.Usage()
return errors.New("one project and --language are required")
}
selected, err := selectAgents(*selection, home)
if err != nil {
return err
}
local := discoverLocalExtensions(stderr)
target, err := generate(flags.Arg(0), *language, home, selected, local, *force)
if err != nil {
return err
}
names := strings.Join(selected, ", ")
if names == "" {
names = "none"
}
fmt.Fprintf(out, "Created %s; agents: %s\n", target, names)
if len(local) > 0 {
fmt.Fprintf(out, "Included %d local VS Code extensions.\n", len(local))
}
fmt.Fprintln(out, "Open the project in VS Code and choose Dev Containers: Reopen in Container.")
return nil
}
func main() {
home, err := os.UserHomeDir()
if err == nil {
err = run(os.Args[1:], home, os.Stdout, os.Stderr)
}
if errors.Is(err, flag.ErrHelp) {
return
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View File

@@ -0,0 +1,281 @@
package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
func setup(t *testing.T) (string, string) {
t.Helper()
root := t.TempDir()
home, project := filepath.Join(root, "host home"), filepath.Join(root, "project with spaces")
for _, path := range []string{home, project} {
if err := os.MkdirAll(path, 0755); err != nil {
t.Fatal(err)
}
}
return home, project
}
func read(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return string(b)
}
func put(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
t.Fatal(err)
}
}
type vscodeCustomizations struct {
Customizations struct {
Vscode struct {
Extensions []string `json:"extensions"`
} `json:"vscode"`
} `json:"customizations"`
}
func extensionsOf(t *testing.T, target string) []string {
t.Helper()
var config vscodeCustomizations
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
t.Fatal(err)
}
return config.Customizations.Vscode.Extensions
}
func TestProfiles(t *testing.T) {
for name := range profiles {
t.Run(name, func(t *testing.T) {
home, project := setup(t)
target, err := generate(project, name, home, nil, nil, false)
if err != nil {
t.Fatal(err)
}
var config map[string]any
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
t.Fatal(err)
}
if config["containerEnv"].(map[string]any)["HOME"] != home {
t.Fatal("wrong home")
}
if _, ok := config["postCreateCommand"]; ok {
t.Fatal("unexpected agent install")
}
want := append([]string{}, profiles[name].Extensions...)
slices.Sort(want)
if got := extensionsOf(t, target); !slices.Equal(got, want) {
t.Fatalf("wrong extensions: %v", got)
}
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
if !strings.HasPrefix(dockerfile, "FROM "+profiles[name].Image+"\n") || !strings.HasSuffix(dockerfile, "USER vscode\n") {
t.Fatal("wrong Dockerfile")
}
})
}
}
func TestSharedConfig(t *testing.T) {
home, project := setup(t)
put(t, filepath.Join(home, ".codex/auth.json"), "secret-value")
put(t, filepath.Join(home, ".gitconfig"), "[user]\nname = Test\n")
target, err := generate(project, "python", home, []string{"codex"}, nil, false)
if err != nil {
t.Fatal(err)
}
configText := read(t, filepath.Join(target, "devcontainer.json"))
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
if strings.Contains(configText+dockerfile, "secret-value") {
t.Fatal("credential leaked")
}
var config struct {
Mounts []mount
PostCreateCommand string
}
if err := json.Unmarshal([]byte(configText), &config); err != nil {
t.Fatal(err)
}
foundGit, foundAgent := false, false
for _, m := range config.Mounts {
if m.Target == "/run/host-gitconfig" {
foundGit = m.ReadOnly
}
if m.Target == filepath.Join(home, ".codex") {
foundAgent = !m.ReadOnly
}
}
if !foundGit || !foundAgent || !strings.Contains(dockerfile, "include.path /run/host-gitconfig") {
t.Fatal("incorrect sharing")
}
if !strings.Contains(config.PostCreateCommand, "@openai/codex") || !strings.Contains(dockerfile, "COPY --from=node /usr/local/bin/node") {
t.Fatal("missing CLI install or embedded Node")
}
if !slices.Contains(extensionsOf(t, target), "openai.chatgpt") {
t.Fatal("agent VS Code extension missing")
}
}
func TestAgentAndLocalExtensions(t *testing.T) {
home, project := setup(t)
put(t, filepath.Join(home, ".cline/state/config"), "")
put(t, filepath.Join(home, ".agents/AGENTS.md"), "")
local := []string{"github.remotehub", "SAOUDRIZWAN.claude-dev", "ms-vscode.cpptools"}
target, err := generate(project, "python", home, []string{"cline"}, local, false)
if err != nil {
t.Fatal(err)
}
want := []string{"ms-python.python", "charliermarsh.ruff", "saoudrizwan.claude-dev", "github.remotehub", "ms-vscode.cpptools"}
slices.Sort(want)
if got := extensionsOf(t, target); !slices.Equal(got, want) {
t.Fatalf("extensions mismatch: %v", got)
}
}
func TestAgentsShipNpmInsideSudoPath(t *testing.T) {
for name := range profiles {
t.Run(name, func(t *testing.T) {
home, project := setup(t)
put(t, filepath.Join(home, ".cline/state/config"), "")
put(t, filepath.Join(home, ".agents/AGENTS.md"), "")
target, err := generate(project, name, home, []string{"cline"}, nil, false)
if err != nil {
t.Fatal(err)
}
var config map[string]any
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
t.Fatal(err)
}
if _, hasFeature := config["features"]; hasFeature {
t.Fatal("the nvm-based node feature breaks the sudo npm postCreateCommand")
}
post, _ := config["postCreateCommand"].(string)
if !strings.Contains(post, "sudo npm install") {
t.Fatalf("missing npm agent install: %q", post)
}
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
if !strings.HasPrefix(dockerfile, "FROM docker.io/library/node:22-bookworm-slim AS node\n") ||
!strings.Contains(dockerfile, "COPY --from=node /usr/local/bin/node /usr/local/bin/node") ||
!strings.Contains(dockerfile, "ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm") {
t.Fatal("npm must be reachable inside sudo's secure_path")
}
})
}
}
func TestOverwriteAndSymlinks(t *testing.T) {
home, project := setup(t)
target, err := generate(project, "go", home, nil, nil, false)
if err != nil {
t.Fatal(err)
}
before := read(t, filepath.Join(target, "Dockerfile"))
if _, err := generate(project, "rust", home, nil, nil, false); err == nil {
t.Fatal("overwrote existing configuration")
}
path := filepath.Join(target, "devcontainer.json")
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
victim := filepath.Join(home, "victim")
put(t, victim, "keep")
if err := os.Symlink(victim, path); err != nil {
t.Fatal(err)
}
if _, err := generate(project, "rust", home, nil, nil, true); err == nil {
t.Fatal("accepted symlink")
}
if read(t, victim) != "keep" || read(t, filepath.Join(target, "Dockerfile")) != before {
t.Fatal("changed files before rejecting symlink")
}
}
func TestInvalidInputs(t *testing.T) {
for _, kind := range []string{"agent", "language", "missing-directory", "home", "target-symlink"} {
t.Run(kind, func(t *testing.T) {
home, project := setup(t)
language := "go"
var selected []string
switch kind {
case "agent":
selected = []string{"codex"}
case "language":
language = "unknown"
case "missing-directory":
project = filepath.Join(project, "missing")
case "home":
home = "/"
case "target-symlink":
if err := os.Symlink(home, filepath.Join(project, ".devcontainer")); err != nil {
t.Fatal(err)
}
}
if _, err := generate(project, language, home, selected, nil, true); err == nil {
t.Fatal("invalid input accepted")
}
if exists(filepath.Join(project, ".devcontainer/Dockerfile")) {
t.Fatal("wrote invalid configuration")
}
})
}
}
func TestAgentSelection(t *testing.T) {
home, _ := setup(t)
put(t, filepath.Join(home, ".codex/config.toml"), "")
got, err := selectAgents("auto", home)
if err != nil || strings.Join(got, ",") != "codex" {
t.Fatalf("auto: %v %v", got, err)
}
got, err = selectAgents("codex,codex", home)
if err != nil || len(got) != 1 {
t.Fatal("duplicate agents")
}
if _, err := selectAgents("invalid", home); err == nil {
t.Fatal("unknown agent accepted")
}
}
func TestCLI(t *testing.T) {
for _, first := range []bool{true, false} {
t.Run(map[bool]string{true: "project-first", false: "flags-first"}[first], func(t *testing.T) {
home, project := setup(t)
args := []string{"--language", "go", "--agents", "none", project}
if first {
args = []string{project, "--language", "go", "--agents", "none"}
}
var out bytes.Buffer
if err := run(args, home, &out, &out); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "agents: none") {
t.Fatal("missing output")
}
})
}
}
func TestLocalExtensionDiscovery(t *testing.T) {
bin := t.TempDir()
script := filepath.Join(bin, "code")
if err := os.WriteFile(script, []byte("#!/bin/sh\necho a.b\necho c.d\n"), 0755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
home, project := setup(t)
var out bytes.Buffer
if err := run([]string{project, "--language", "go", "--agents", "none"}, home, &out, &out); err != nil {
t.Fatal(err)
}
want := []string{"a.b", "c.d", "golang.go"}
slices.Sort(want)
if got := extensionsOf(t, filepath.Join(project, ".devcontainer")); !slices.Equal(got, want) {
t.Fatalf("extensions mismatch: %v", got)
}
if !strings.Contains(out.String(), "Included 2 local VS Code extensions.") {
t.Fatal("missing local extensions summary")
}
}

View File

@@ -0,0 +1,18 @@
package main
var profiles = map[string]profile{
"c-cpp": {Image: "mcr.microsoft.com/devcontainers/base:bookworm", Packages: "build-essential clang clangd cmake gdb valgrind universal-ctags cscope", Extensions: []string{"ms-vscode.cpptools", "ms-vscode.cmake-tools"}},
"go": {Image: "mcr.microsoft.com/devcontainers/go:1.25-bookworm", Packages: "", Extensions: []string{"golang.go"}},
"rust": {Image: "mcr.microsoft.com/devcontainers/rust:1-bookworm", Packages: "", Extensions: []string{"rust-lang.rust-analyzer"}},
"python": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "", Extensions: []string{"ms-python.python", "charliermarsh.ruff"}},
"node": {Image: "mcr.microsoft.com/devcontainers/javascript-node:22-bookworm", Packages: "", Extensions: []string{"esbenp.prettier-vscode"}},
"java": {Image: "mcr.microsoft.com/devcontainers/java:21-bookworm", Packages: "maven", Extensions: []string{"vscjava.vscode-java-pack"}},
"infra": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "shellcheck shfmt", Extensions: []string{"redhat.ansible", "redhat.vscode-yaml"}},
}
var agents = map[string]agent{
"codex": {Package: "@openai/codex", Extension: "openai.chatgpt", Paths: []string{".codex"}},
"cline": {Package: "cline", Extension: "saoudrizwan.claude-dev", Paths: []string{".cline", ".agents"}},
"opencode": {Package: "opencode-ai", Extension: "sst-dev.opencode", Paths: []string{".config/opencode", ".local/share/opencode", ".local/state/opencode"}},
"claude": {Package: "@anthropic-ai/claude-code@2.1.312", Extension: "anthropic.claude-code", Paths: []string{".claude"}},
"gemini": {Package: "@google/gemini-cli", Extension: "Google.geminicodeassist", Paths: []string{".gemini"}},
}

159
docs/ai-media-presets.md Normal file
View File

@@ -0,0 +1,159 @@
# Preset offline `ai-media`
## Volume cifrato Backup (Ikaros)
```bash
ai-media mount # sblocca Backup e rende disponibili i file di ai-media
ai-media umount # smonta prima il bind, poi Backup, e richiude LUKS
```
Eseguire i comandi come utente desktop, da un terminale: UDisks chiede la
passphrase LUKS se il volume è chiuso e systemd può chiedere l'autenticazione
amministrativa. La passphrase non viene salvata dal launcher. Prima di
`umount`, chiudere FaceFusion/RVC, attendere i job dei preset e chiudere file
e terminali aperti sul disco. Il comando riguarda **tutto il volume Backup**,
non solo la directory di ai-media, e non forza lo smontaggio. Non scollegare
il disco se il comando segnala un errore.
## Preset disponibili
Tutti i preset video accettano un nome MP4 locale oppure un URL HTTP(S).
I file locali vanno in `~/.local/share/ai-media/input/`. I preset avviano un servizio
`systemd --user` e tornano subito; FaceFusion e RVC restano nei container
offline. Il terminale stampa il nome del job e il comando per seguirne i log.
```bash
# 1. Estrae l'audio, separa voce/strumentale, converte tutta la traccia
# vocale con mia_voce e restituisce solo l'audio finale mixato.
ai-media preset audio-convert video1.mp4
# 2. Applica source11.jpg ... source18.jpg al video: conserva l'audio
# originale se presente, altrimenti produce un video senza audio.
ai-media preset video-convert video1.mp4
# 3. Unisce un video in input/ con un audio presente in input/ oppure output/.
ai-media preset merge video1.mp4 audio.wav
# 4. Esegue voce e volti, poi unisce il video modificato con l'audio convertito.
# Se l'input è un URL, scarica prima un singolo video con yt-dlp.
ai-media preset convert 'https://esempio.org/video'
# 5. Separa il video (senza ricodificarlo) dalla prima traccia audio.
ai-media preset split video1.mp4
# 6. Come split, poi separa l'audio in voce e strumentale, senza convertirne la voce.
ai-media preset split-stems video1.mp4
# 7. Sovrappone voce e strumentale in un unico audio (non concatena le tracce).
ai-media preset mix vocals.wav instrumental.wav
# 8. Applica mia_voce direttamente a un audio, senza separazione né remix.
ai-media preset voice-convert voce.wav
```
## Applicare mia_voce a un audio
```bash
ai-media preset voice-convert voce.wav
ai-media preset voice-convert video1-split-stems/vocals.wav --output video1-mia_voce.wav
```
`voice-convert` legge un audio locale in `input/` oppure `output/`, anche in
una sottocartella, e produce `output/<nome-audio>-mia_voce.wav`. `--output`
permette di scegliere un altro nome WAV. Converte prima la traccia in WAV e
applica direttamente il modello RVC `mia_voce` con il relativo indice e RMVPE,
senza BS Roformer e senza aggiungere lo strumentale. Usare preferibilmente
una voce isolata: il preset non rimuove musica né separa parlanti.
Accetta i formati audio decodificabili dal FFmpeg installato. Richiede il
modello e l'indice personali già presenti nello stato RVC, funziona offline
in background, conserva l'originale e rifiuta risultati già esistenti.
Gli intermedi restano nella sottocartella nascosta del job in `output/`.
Per rimettere lo strumentale dopo la conversione:
```bash
ai-media preset mix video1-mia_voce.wav video1-split-stems/instrumental.wav --output video1-mix.wav
```
## Unire voce e strumentale
`mix` usa due audio locali in `input/` o `output/`, anche nelle sottocartelle
create da `split-stems`:
```bash
ai-media preset mix video1-split-stems/vocals.wav video1-split-stems/instrumental.wav --output video1-mix.wav
```
Il risultato è `output/video1-mix.wav`, PCM WAV a 16 bit. Senza `--output`,
il nome è `<nome-vocale>-mix.wav` (per esempio `vocals-mix.wav`). Le tracce
partono insieme da zero e vengono sommate a volume originale, senza
normalizzazione; la durata è quella della traccia più lunga. Livelli troppo
alti possono causare clipping. Il preset non esegue separazione o conversione
vocale, non modifica gli originali e non sovrascrive file esistenti. Parte in
background come gli altri preset e usa solo FFmpeg nel container offline.
Gli audio devono essere univoci tra `input/` e `output/`; percorsi assoluti,
`..`, link simbolici e URL audio non sono accettati.
## Video da URL
Per ogni preset video si può sostituire il nome del video con un URL tra virgolette:
```bash
ai-media preset split 'https://esempio.org/video'
ai-media preset split-stems 'https://esempio.org/video'
ai-media preset audio-convert 'https://esempio.org/video'
ai-media preset video-convert 'https://esempio.org/video'
ai-media preset merge 'https://esempio.org/video' audio.wav
ai-media preset convert 'https://esempio.org/video'
# Anche convert accetta un file locale, senza download:
ai-media preset convert video1.mp4
```
Il download con `yt-dlp` avviene una sola volta nello stesso job in background,
prima dell'elaborazione. Il video scaricato resta in `input/download-<ID>.mp4`;
i risultati usano lo stesso prefisso `download-<ID>` al posto di `video1`.
Serve `yt-dlp` sull'host solo per gli URL. L'audio di `merge` rimane un file
locale in `input/` oppure `output/`. URL locali/privati o contenenti credenziali
non vengono accettati. Se il download fallisce, l'elaborazione non parte.
`split` produce `output/video1-split/video.mp4` (muto) e `audio.wav`.
`split-stems` produce `output/video1-split-stems/` con `video.mp4`, `audio.wav`,
`vocals.wav` e `instrumental.wav`. L'audio estratto è PCM WAV a 16 bit;
la separazione usa BS Roformer offline nel container RVC e non richiede
il modello personale `mia_voce`. Entrambi richiedono un video con audio,
non modificano l'originale e rifiutano una cartella risultato già esistente.
Mantengono gli intermedi nella sottocartella nascosta del job in `output/`;
i risultati pubblicati sono hard link e non duplicano lo spazio dei file.
`video-convert` e il passaggio video di `convert` usano lo stesso profilo
FaceFusion: HyperSwap 1a 256 (pixel boost 256x256, peso 0.5), rilevatore
`yolo_face` 640x640 agli angoli 0/90/180/270, selezione `one` per volto
grande, filtri `female` e `white`, maschere `occlusion region area box` con
`xseg_1` e `bisenet_resnet_34` (blur 0.3), H.264 `libx264` veryfast, qualità
80 e 30 fps. L'audio originale viene ripristinato separatamente quando esiste.
Risultati: `output/video1-mia_voce.wav`, `output/video1-facefusion.mp4` e
`output/video1-unito.mp4`. Il preset `convert` crea
`output/video1-completo.mp4` (o `output/download-<ID>-completo.mp4` da URL),
mantenendo anche l'audio e il video intermedi. Richiede `source11.jpg`–`source18.jpg`
in `input/` e un video che contenga audio. **Solo il download** tramite
`yt-dlp` usa la rete; non usa la configurazione o i cookie personali di
`yt-dlp` e non scarica playlist. I file esistenti non vengono sovrascritti. Il
primo e il secondo preset conservano i passaggi intermedi in una sottocartella
`.video1-...` di `output/`, utile per diagnosi e recupero; non viene rimossa
automaticamente.
Per controllare un job, usare il nome stampato dal comando:
```bash
journalctl --user -fu ai-media-preset-YYYYMMDD-HHMMSS-ID
systemctl --user status ai-media-preset-YYYYMMDD-HHMMSS-ID
```
Il preset `audio-convert` converte l'intero stem vocale: non distingue automaticamente
voci maschili e femminili e non separa parlanti sovrapposti. L'elaborazione è
in background, **non** più rapida della capacità della CPU. I nomi dei video locali
devono essere semplici, senza percorsi; gli audio possono indicare sottocartelle
relative a `input/` o `output/`. Se lo stesso audio
è in `input/` e `output/`, il comando rifiuta l'ambiguità. Tutti i video di
input dei preset devono essere MP4 con un nome diverso dal risultato atteso.

View File

@@ -0,0 +1,42 @@
# Atlas Gitea container registry
The existing Gitea instance provides an OCI container registry at
`git.fscotto.co`. Gitea 1.25.2 enables packages by default; no separate
container, port, DNS record, or registry service is required. The existing
Gitea HTTPS proxy route is used. The setting applies to Gitea's package
registry generally, not only container images.
On 2026-10-25, both the Atlas HTTP endpoint and the public HTTPS `/v2/`
endpoint returned the expected `401` bearer authentication challenge. NPM's
effective `client_max_body_size` was `2000m`; larger individual requests may
be rejected. Authentication and an actual image push and pull have not yet
been tested. Do not interpret the unauthenticated challenge as a complete test.
## Use with Podman
Replace `OWNER`, `IMAGE`, and `TAG` with your Gitea user or organization and
image details. Log in interactively; use a personal access token when using
two-factor authentication. Do not put credentials in commands or shell history.
```sh
podman login git.fscotto.co
podman tag LOCAL_IMAGE:TAG git.fscotto.co/OWNER/IMAGE:TAG
podman push git.fscotto.co/OWNER/IMAGE:TAG
podman pull git.fscotto.co/OWNER/IMAGE:TAG
```
Choose the package's visibility and access deliberately in Gitea. Check the
package page and verify the pulled image digest when testing. No automatic
cleanup policy is configured by this document.
## Data and recovery
The observed package storage directory is
`/zpool/services/data/gitea/data/gitea/packages`, inside the existing Gitea
dataset. Package metadata also depends on the Gitea database and configuration.
Existing recursive ZFS and backup coverage must include both, but a successful
registry-specific backup and restore has not been tested. Review backup capacity
and consistency as image storage grows; a snapshot alone is not proof of an
application-consistent restore.
Reference: https://docs.gitea.com/1.25/usage/packages/container/

View File

@@ -141,11 +141,22 @@ See `atlas-nextcloud-recovery-test.md` for scope, retained artifact and limitati
## Recurring consistent bundles
`atlas-nextcloud-backup.service` is now an ordered requirement of both
`atlas-nextcloud-backup.service` is an ordered requirement of both
`atlas-borg-backup.service` and the operator-started `atlas-usb-backup.service`.
No additional backup timer is needed: the existing Borg schedule prepares a fresh
bundle before its pool snapshot, and a manual USB run does the same. Preparation
failure blocks the dependent job rather than silently using an old dump.
bundle before its pool snapshot. A structurally complete bundle from an earlier
verified run is reused instead while younger than
`atlas_nextcloud_backup_reuse_max_seconds` (20 h): a manual USB run then skips
the application pause, reaches its LUKS prompt within seconds and captures the
latest Borg-prepared bundle, while the remaining pool snapshot reflects the
moment of the run. Reuse does not re-hash the bundle; it was checksum-verified
at publication. The window is asserted below 24 h so the nightly Borg run,
spaced 24 h plus its randomized delay, never reuses the previous night's bundle.
Preparation failure still blocks the dependent job rather than silently using an
old dump; only a verified, bounded-age bundle may be reused. Set
`ATLAS_NEXTCLOUD_BACKUP_FORCE=1` with `systemctl set-environment` (the unit
passes it through) to ignore the window once and prepare a fresh bundle; unset
the variable afterwards.
The helper checks the mounted datasets and healthy active application state,
serializes preparations and briefly pauses cron, Nextcloud and ONLYOFFICE. It
@@ -171,10 +182,12 @@ sudo systemctl start atlas-nextcloud-backup.service
sudo systemctl show atlas-nextcloud-backup.service -p Result -p ExecMainExitTimestamp
```
The second command briefly interrupts the applications and is an explicit manual
run of the recurring job, not a normal deployment side effect. The preparation
unit is not enabled as a boot backup; only interrupted-job recovery is enabled.
Do not stop a Borg/USB job, break its lock or unmount its source snapshot to run a test.
A manual start briefly interrupts the applications only when it prepares a fresh
bundle; inside the reuse window it logs `Reusing verified ...` and finishes in
seconds without touching them. It remains an explicit manual run of the
recurring job, not a normal deployment side effect. The preparation unit is not
enabled as a boot backup; only interrupted-job recovery is enabled. Do not stop a
Borg/USB job, break its lock or unmount its source snapshot to run a test.
On 2026-10-04, both a new encrypted Borg archive and USB version
`20261004T101101Z-3420114` were independently extracted and their consistent
@@ -193,7 +206,7 @@ Nextcloud container, using shared SELinux `:z` labels:
| Nextcloud folder | Host directory | Access |
| --- | --- | --- |
| `Documenti` | `/zpool/archive/Documents` | Read/write |
| `Foto iCloud` | `/zpool/archive/Pictures/iCloudPD` | Read-only |
| `Photos` | `/zpool/archive/Pictures/iCloudPD` | Read-only |
Both system mounts are restricted to the Nextcloud user `fabio` only; `chiara`
and the `famiglia` group have no access through these mounts.
@@ -262,8 +275,11 @@ search, not lack of recursive indexing.
The user preference `photosSourceFolders` was changed directly from
`["/Photos","/Foto iCloud"]` to `["/Foto iCloud"]`, after verifying no indexed
media under the personal Photos directory. No original files were moved or
modified, and no permanent one-time repair task was added to Ansible.
media under the personal Photos directory. On 2026-10-10, the managed external
mount was renamed to `Photos`; after the old mount configuration is removed on
the live instance, the source preference must be `['/Photos']`. No original
files are moved or modified: `Photos` remains a read-only direct view of
`/zpool/archive/Pictures/iCloudPD`, with iCloudPD as the sole writer.
The diagnostic app password was revoked. Browser display confirmation remains
with the operator; this check does not establish mobile-gallery behavior.

80
docs/atlas-paperless.md Normal file
View File

@@ -0,0 +1,80 @@
# Paperless-ngx on Atlas
Atlas runs Paperless-ngx as six `admin`-owned rootless Quadlets:
Paperless 3.2.1, PostgreSQL 17, Valkey 8, Apache Tika 3.3.1.0 and
Gotenberg 8.37, and Ollama 0.40.3. State is isolated beneath
`zpool/services/data/paperless` in `data`, `media`, `consume`, `database` and
`cache`, and `ollama` datasets, so recursive ZFS snapshots, Borg and the UUID-bound USB
backup cover it without an application-specific backup job.
The only published listener is `192.168.178.55:8002`; Atlas firewalld admits it
only from Aegis. The database, broker and Office converters have no host
listener. Paperless is
configured with the canonical public URL `https://documents.fscotto.co`.
Ollama has no published host port and is reachable only on the private Paperless
container network. Paperless uses `qwen2.5:1.5b-instruct-q4_K_M` for suggestions
and chat and `nomic-embed-text:v1.5` for local document embeddings. Its context
is capped at 2048 tokens; Ollama is limited to 3 GiB, one loaded
model and one parallel request because Atlas has little spare RAM. Model files
are downloaded once from the Ollama registry; documents are not sent there.
The small language model trades answer quality and speed for resource safety.
Review AI-generated suggestions and answers before relying on them.
After the first deployment, build the LLM index when convenient (it may take
time and CPU proportional to the document count):
```sh
sudo -iu admin XDG_RUNTIME_DIR=/run/user/1000 \
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
podman exec atlas-paperless document_llmindex rebuild
```
The scheduled incremental index update runs daily. After changing the
embedding model, rebuild the index again. App Configuration values in the
Paperless database take precedence over environment variables, so avoid setting
AI endpoint/backend overrides in the UI if Ansible should remain authoritative.
Tika and Gotenberg enable DOCX and other Office imports. Paperless retains the
original and produces a PDF rendition; this does not add in-browser editing.
Gotenberg disables Chromium JavaScript and restricts file access for email
conversion. A targeted role run probes both converters from inside Paperless.
## Initial deployment
The required encrypted-Vault fields are `vault_paperless_database_password`
and `vault_paperless_secret_key`; do not place them in host variables or paste
them into chat. Generate unique values through the local Vault workflow before
the first run. The service assertion deliberately rejects absent or weak
values.
Deploy with:
```sh
ANSIBLE_LOCAL_TEMP=/tmp/ansible-local \
ansible-playbook ansible/site.yml --limit atlas --tags paperless --check --diff
ANSIBLE_LOCAL_TEMP=/tmp/ansible-local \
ansible-playbook ansible/site.yml --limit atlas --tags paperless
```
After it is healthy, add an NPM Proxy Host manually on Prometheus for
`documents.fscotto.co` to `http://192.168.178.55:8002`, request its TLS
certificate, and keep Websocket Support enabled. DNS and NPM remain explicit
operations and are not changed by the Paperless role.
Create the initial Paperless administrator interactively from an Atlas SSH
session; do not put an initial user password in the playbook or Vault:
```sh
sudo -iu admin XDG_RUNTIME_DIR=/run/user/1000 \
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
podman exec -it atlas-paperless document_index reindex
sudo -iu admin XDG_RUNTIME_DIR=/run/user/1000 \
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
podman exec -it atlas-paperless createsuperuser
```
The first command is optional for a new empty instance; it is included as a
safe way to ensure the index is current before using Paperless. Put scanned
files in the private `consume` dataset only via an intentionally configured
source; Paperless consumes and moves them into its managed media store.

View File

@@ -0,0 +1,43 @@
# cdp Java 25 / Node 20 dev container on deadalus
Same toolset and mounts as the [ecaas container](deadalus-ecaas-devcontainer.md)
(Git configuration and GitLab CAs, Bash configuration, `~/.m2`, `~/.claude`,
`~/.cline`, `~/.agents`, `~/.config/ai`, Docker outside of Docker, Claude Code,
Cline, delta, Great Icons), with these differences:
- Java 25 (`mcr.microsoft.com/devcontainers/java:25-bookworm`) is the default JDK
and also runs the Java and Spring language servers; there is no second JDK.
- Maven is `workstation_maven_version`; Node is
`workstation_cdp_node_version` (20.18.3) from the official Node image, used by
the Angular Module Federation front ends and the Claude/Cline CLIs.
- Angular Language Service and ESLint are added; forwarded ports are 4200, 4201,
4202, 4210 (front ends) and 8083, 8084 (`mediation-ansc`, `ansc-allegati`).
- `kubectl` 1.37.1 and Helm 4.2.2 are installed from the official releases with
pinned SHA-256 checksums (amd64 and arm64), and the Kubernetes VS Code
extension is added. The WSL `~/.kube` is bind-mounted read-write at
`/home/vscode/.kube`, so contexts, tokens and cached data are shared with the
host; the current `config` embeds the Rancher CA and credentials, which are
therefore readable by anything in the container. The Rancher endpoint must be
reachable from the container (VPN). `KUBECONFIG` on the host is not forwarded.
- `glab` 1.114.0 (pinned checksum) is installed and `~/.config/glab-cli` is
mounted read-write, as described in the ecaas document (tokens included).
Legacy `serv_roma-capitale-*` modules target Java 21 / Spring Boot 3.3.4 and
are not covered by this image's JDK.
The workspace is multi-repo and not a Git repository itself; open
`~/Work/sipo/cdp` from Fedora WSL. Maven needs the internal Nexus (VPN) and
`-s settings.xml`, as described in the workspace `AGENTS.md`.
```sh
ansible-playbook ansible/site.yml --limit deadalus --tags cdp_devcontainer -K
```
The deploy writes `~/Work/sipo/cdp/.devcontainer/` (`devcontainer.json`,
`Dockerfile`, `bashrc`, `bashrc.aliases`), backing up changed files. It shares
the rendered Git configuration in `~/.local/state/ecaas-devcontainer/git` with
the ecaas container and therefore also requires the ecaas GitLab CA. Then run
**Dev Containers: Reopen in Container**. The `ANTHROPIC_AUTH_TOKEN` forwarding
and credential caveats are the same as for ecaas.
Verify inside: `java -version`, `mvn -v`, `node -v` (v20.18.3), `docker info`.

View File

@@ -0,0 +1,125 @@
# ecaas Java 11 dev container on deadalus
From the AnsiblePlaybook checkout **in Fedora WSL 2 on deadalus**:
```sh
ansible-playbook ansible/site.yml --limit deadalus --tags ecaas_devcontainer -K
```
This creates `~/Work/sipo/ecaas/.devcontainer/` and deploys `devcontainer.json`,
`Dockerfile` and `bashrc`, backing up previous versions if they change. It does
not clone or modify application sources, change VS Code's Windows settings, or
start Docker containers. The Docker context selection remains in the local
WSL/VS Code setup.
Confirm that `docker context show` is `default` and `docker info` shows the local
Fedora engine. Open `~/Work/ecaas` using `code .` from Fedora and select
**Dev Containers: Reopen in Container** (or **Rebuild Container** if already open).
Do not use the production context to build or open the workspace.
The container uses Java 11 for the application and Maven, and Java 21 only for
the Java and Spring language servers. VS Code installs the Java and Spring Boot
extension packs, XML, YAML, the Cline extension and the VSCode Great Icons theme
(selected as the file icon theme) inside the container. The Java
pack includes Maven, the Java debugger and test integration. Prefer the project's
Maven wrapper where present. Node is provided for the Claude and Cline CLIs.
Git is installed in the container. The image uses the repository's portable Bash
configuration: prompt with Git status, aliases, history search, completion,
`fzf` and `zoxide`. The shared `.bashrc.aliases` is copied minus the
production `npm-tunnel` alias. The image
does not load the WSL host's production aliases or Bash history.
Run the deploy and rebuild the container to pick up changes to the shared Bash
configuration.
## Git, HTTPS, and SSH
The image provides Git, Git LFS, delta, OpenSSH and GnuPG. It includes the
managed workstation Git configuration from a read-only mount at runtime,
with VS Code rather than Bob as the diff and merge tool. Git identity and
signing configuration stay outside the workspace and image layers.
Before deploying, ensure the existing WSL certificate
`~/.local/share/certs/ecaas.datacenter.comune.roma.crt` is available. The
playbook checks and mounts that file read-only. It also mounts
`datacenter.comune.roma.crt` from the same directory if present. These files
are scoped to their GitLab URLs in Git; the image does not disable TLS
verification or add the internal certificates to its global trust store.
Recreate the container after replacing a certificate on the host.
Open the project from Fedora WSL so VS Code Dev Containers can reuse WSL's
HTTPS credential helper (including an existing `.git-credentials` used by
`credential.helper=store`) and forward the SSH agent if configured. GPG
signing remains enabled and needs the work key available through the GPG
agent. The WSL `~/.m2` (repository cache and `settings*.xml`, which may hold Maven
server credentials) is bind-mounted read-write at `/home/vscode/.m2`. No other
credential file, SSH private key, or GPG private key is copied or mounted by
the playbook. Do not forward a production SSH identity to this
development workspace.
To verify GitLab access from the container without changing the repo, run
`git ls-remote origin HEAD` after checking that `origin` is the expected
GitLab repository.
## Docker
The `docker-outside-of-docker` Dev Container feature installs the Docker CLI
and Compose plugin and shares the local Fedora WSL engine's socket
(`/var/run/docker.sock`) with the container. Containers started from inside are
siblings on the WSL engine, and bind-mount sources resolve on the WSL host.
The socket grants root-equivalent control of that engine, and the container
never sees the host's Docker contexts, so the production context is
unreachable. Verify with `docker info` and `docker compose version`.
## GitLab CLI
`glab` 1.114.0 is installed from the official `.deb` with a pinned SHA-256
checksum (amd64 and arm64). The WSL `~/.config/glab-cli` is bind-mounted
read-write at `/home/vscode/.config/glab-cli`, so hosts, API tokens and
`skip_tls_verify` settings are shared with the host and readable by anything in
the container; changes made by `glab` inside affect the WSL configuration.
`GITLAB_TOKEN` and similar variables from the host are not forwarded.
## Agent configuration and smoke test
Claude and Cline use the WSL configuration directly: `~/.claude` and `~/.cline`
are bind-mounted read-write at `/home/vscode/.claude` and `/home/vscode/.cline`,
the cross-tool `~/.agents` read-only at `/home/vscode/.agents`, and
`~/.config/ai` read-only at `/home/vscode/.config/ai`, so rules, the AGENTS
pointer and the shared AI context follow the WSL host. The playbook keeps
Cline's managed configuration deployed on the host (`cline_deploy_enabled:
true`) even though the cline CLI npm package is not installed there; the CLI
ships inside the image and the VS Code Cline extension is installed through
the devcontainer customizations. Settings, rules,
skills, MCP configuration, sessions and **credential stores** are therefore
shared with, and visible to, the container, and changes made inside it affect
the WSL home. Host paths and tools referenced by rules or skills may need
adaptation. The WSL login is the `ANTHROPIC_AUTH_TOKEN` exported by
`~/.bashrc.d/60-claude-code.sh`, not the OAuth file. `remoteEnv` forwards it with
`${localEnv:ANTHROPIC_AUTH_TOKEN}`: the value is never written to the repository
or the image, but it is visible to processes in the container. VS Code must
therefore be started from a WSL shell that exports it (`code .` after opening a
new terminal; fully close any running VS Code server first). The endpoint and
model come from the mounted `settings.json`. With `CLAUDE_CONFIG_DIR` set, Claude reads its account state from
`~/.claude/.claude.json` instead of `~/.claude.json`, so the playbook seeds the
missing `oauthAccount`, `hasCompletedOnboarding` and `userID` keys there from
the WSL file without overwriting existing keys (`~/.claude.json` itself is not
mounted); VS Code global storage is not shared
either, so legacy Cline settings kept only there are not migrated. The full
host home is not mounted. `~/.local/state/ecaas-devcontainer/` now holds only
the rendered Git configuration.
From the integrated terminal inside the Dev Container, verify:
```sh
java -version
mvn -v
git --version
delta --version
claude --version
cline --version
```
Both Java and Maven should report Java 11. Run the project's Maven tests and
check that the Spring Boot Dashboard, Java debugger and both AI panels open.

View File

@@ -0,0 +1,138 @@
# Reusable project devcontainers
`cmd/devcontainer/` is a Go CLI using only the standard library. Build it with
Go 1.22 or newer, from an `infra` checkout:
```sh
go -C cmd/devcontainer build -o "$HOME/.local/bin/devcontainer" .
```
Create `~/.local/bin` first if needed and keep it on `PATH`. The resulting binary
has no Python dependency. Run it on **the development host**, against an existing
project:
```sh
devcontainer ~/src/my-project --language go
devcontainer ~/src/my-project --language python --agents codex,cline
devcontainer ~/src/my-project --language c-cpp --agents none
```
## Ansible deployment
On ikaros, nymph or deadalus, from the local `infra` checkout:
```sh
ansible-playbook ansible/site.yml --limit ikaros --tags devcontainer_generator -K
```
Replace the limit with `nymph` or `deadalus` as appropriate. The task installs
Fedora's Go compiler, copies the sources into the user's build cache, compiles
natively without downloading Go modules, and installs `~/.local/bin/devcontainer`
with mode `0755`. Subsequent runs update the executable only when its contents
change. Rebuilds use the Go cache. The role targets Fedora graphical desktops
and Fedora development workstations; it does not start any containers.
Check mode validates packages and source deployment but skips compilation and
binary installation, and reports that limitation explicitly:
```sh
ansible-playbook ansible/site.yml --limit ikaros --tags devcontainer_generator --check --diff
```
Profiles: `c-cpp`, `go`, `rust`, `python`, `node`, `java`, `infra`. They generate
`.devcontainer/devcontainer.json` and `Dockerfile`. The generated
`customizations.vscode.extensions` list combines the profile extensions, the VS
Code extension of each selected agent (`cline` → `saoudrizwan.claude-dev`,
`claude` → `anthropic.claude-code`, `codex` → `openai.chatgpt`, `gemini` →
`Google.geminicodeassist`, `opencode` → `sst-dev.opencode`) and every extension
installed in the local VS Code, captured through `code --list-extensions` at
generation time; regenerate after installing or removing extensions on the
host. Without a local VS Code on PATH only the profile and agent extensions are
included. Open the project in local VS
Code (in Fedora WSL on deadalus) and choose **Reopen in Container**. The generator
never builds or starts a container, selects a Docker context, modifies application
sources, or removes host packages. Existing `.devcontainer` directories are refused;
`--force` replaces only the two generated files, so commit or back up edits first.
The definitions live centrally in the generator; generated files are standalone.
Regenerate explicitly to take updates. Profile images select a language version
or release family, not immutable digests; npm agents other than Claude currently
resolve the latest release at container creation, matching the host lifecycle.
Agent containers copy Node from the official `docker.io/library/node` image into
`/usr/local` instead of using the nvm-based node feature, so the
`sudo npm install` postCreateCommand works in every profile.
Rebuilds are therefore not bit-for-bit reproducible. Pin image digests and agent
versions in generated project files when a project requires that guarantee.
Project-specific dependencies, ports, services and build commands belong in the
project configuration. The `infra` profile provides Ansible and linters; install
that project's collection requirements inside it separately.
## Shared Git and agents
Like the ecaas/cdp model, executables run inside the container and personal
configuration stays on the host. The generator detects existing configuration
paths without reading credentials. With `--agents auto` (the default), it selects
agents whose configuration directories already exist. Explicit agent selection
fails if required directories are missing. Supported agents: `codex`, `cline`,
`opencode`, `claude`, `gemini`. IBM Bob and desktop applications are not included.
Host `~/.gitconfig` is mounted read-only at `/run/host-gitconfig` and included from
a writable container Git config, allowing VS Code to register its credential
helper. Existing `~/.config/git` and `~/.gitignore_global` are mounted read-only.
Git, Git LFS, delta, OpenSSH and GnuPG are installed. VS Code Dev Containers handles
SSH-agent and HTTPS credential-helper forwarding; start VS Code from the host
session with its working agent. No SSH/GPG private-key directories are mounted.
GPG signing needs a functioning agent-forwarding setup and a test with your key;
the generator does not provision it. Host-specific helpers, `pinentry`, external
Git includes, conditional includes and CA paths still need container-compatible
configuration or additional narrowly scoped mounts. Recreate the container after
replacing a bind-mounted configuration file atomically on the host.
`~/.config/ai` is mounted read-only when present. Selected agents mount their host
configuration/state directories read-write, including credentials, sessions and
rules; changes inside the container affect the host. OpenCode also shares its
XDG data/state directories. The container user remains `vscode`, with its home set
to the **same absolute path as the generating host**, so Codex's absolute
`model_instructions_file` keeps working. This does not mount the full home.
For a different host home path, regenerate there. Host-only programs referenced
by agent settings are not made available automatically.
Claude also mounts `~/.claude.json` when present and forwards
`ANTHROPIC_AUTH_TOKEN` using `${localEnv:ANTHROPIC_AUTH_TOKEN}` as on deadalus.
Start VS Code from a shell that exports it; no token value is generated. Host
keyring-backed logins require separate integration; sharing a directory does not
forward the desktop keyring. VS Code extension storage is not shared.
Only existing paths are mounted. Regenerate after configuring an additional
agent. Generated files use `${localEnv:HOME}` for mount sources and contain no
credential contents, but do contain the host's absolute home path.
## Runtime and validation
Use a local development container engine. Docker CE is currently provisioned on
deadalus; ikaros explicitly has Podman, while nymph's runtime needs verification.
Podman (5+) works through VS Code's `dev.containers.dockerPath: podman` per the
official Dev Containers documentation: the extension drives the container CLI
and needs neither the `podman-docker` shim nor a daemon socket or `DOCKER_HOST`.
Never install `podman-docker` where docker-ce provides the real Docker CLI
(deadalus). Generation alone does not configure the engine; the `desktop_gnome`
profile deploys `dev.containers.dockerPath: podman` with its managed VS Code
settings, while compatible
rootless/UID configuration and SELinux bind-mount access must be validated on the
Fedora target host. Do not recursively relabel the personal home.
No engine socket is mounted inside these containers by default; add access only
for projects that need to launch sibling containers.
Host-side regression checks:
```sh
go -C cmd/devcontainer test ./...
go -C cmd/devcontainer vet ./...
```
On the target host, build/open a generated project, check the language toolchain,
`git config --show-origin --get user.email`, `git ls-remote origin HEAD` against
the expected development remote, and each selected agent's version/login.
Run project tests and verify signing if enabled. These runtime checks require the
real host and are separate from generator tests. Existing ecaas/cdp Ansible
provisioning is unchanged.

View File

@@ -0,0 +1,6 @@
# Cline Global Context
Load and follow the shared coding-agent context stored under `~/.config/ai/`:
- Operating context: read `~/.config/ai/bootstrap.md`
- Task-specific knowledge, rules, patterns, and ChatGPT memory loading: read `~/.config/ai/AGENTS.md`

View File

@@ -3,3 +3,7 @@
Import the shared coding agent bootstrap context:
@~/.config/ai/bootstrap.md
Import the shared task-specific file dispatcher (knowledge, rules, and ChatGPT memory):
@~/.config/ai/AGENTS.md

View File

@@ -0,0 +1,23 @@
# Deployed global AI context
The standing AI context for this user is deployed by the Ansible-managed
dotfiles under `~/.config/ai/` and is maintained in the infrastructure
repository. Cline binds to it automatically in every project through this
global rule.
- Operating context: read `~/.config/ai/bootstrap.md` first. It carries the
persistent mental model: core principles, system and infrastructure models,
and agent behavior.
- Safety directives: apply `~/.config/ai/rules/safety.md`.
- Task-specific loading: follow the dispatcher `~/.config/ai/AGENTS.md` and
read only the files relevant to the current task from `knowledge/`, `rules/`,
and `patterns/`. Do not preemptively load all task-specific files.
- Distilled knowledge: for prior decisions, history, and stable preferences,
start from `~/.config/ai/memory/chatgpt/INDEX.md` and read the matching
topic file under `~/.config/ai/memory/chatgpt/knowledge/`. When that is not
enough, search the full transcripts with
`rg -i "<keyword>" ~/.config/ai/memory/chatgpt/transcripts/`.
These deployed files are managed state: never record session-specific notes in
them. Update them in the source infrastructure repository instead, so the next
playbook run converges the change everywhere.

View File

@@ -0,0 +1,7 @@
# Codex Global Context
Import the shared coding agent bootstrap context:
@~/.config/ai/bootstrap.md
Follow the task-specific file loading described in `~/.config/ai/AGENTS.md` (knowledge, rules, and ChatGPT memory).

View File

@@ -1,4 +1,3 @@
model = "gpt-5.6-terra"
model_reasoning_effort = "medium"
model_instructions_file = "{{ effective_user_home }}/.config/ai/bootstrap.md"

View File

@@ -1,15 +1,19 @@
# AGENTS.md — Global Context
# AGENTS.md — Global Context (dispatcher)
Always follow:
- minimal, targeted edits
- preserve layering
- avoid duplication
- validate before applying changes
- safety directives: always apply `~/.config/ai/rules/safety.md`
Task-specific file loading:
- For infra or Ansible work, read `~/.config/opencode/knowledge/infra.md` and `~/.config/opencode/rules/ansible.md`
- For desktop work, read `~/.config/opencode/knowledge/desktop.md`
- For dotfiles work, read `~/.config/opencode/knowledge/dotfiles.md` and `~/.config/opencode/patterns/dotfiles_layering.md`
- For system programming work, read `~/.config/opencode/knowledge/system_programming.md`
- For general background on the user, the environment, and stable preferences, read `~/.config/ai/memory/chatgpt/knowledge/00-profilo.md`
- For infra or Ansible work, read `~/.config/ai/knowledge/infra.md` and `~/.config/ai/rules/ansible.md`
- For desktop work, read `~/.config/ai/knowledge/desktop.md`
- For dotfiles work, read `~/.config/ai/knowledge/dotfiles.md` and `~/.config/ai/patterns/dotfiles_layering.md`
- For system programming work, read `~/.config/ai/knowledge/system_programming.md`
- For prior ChatGPT discussion context (past decisions, history, preferences, projects), start from `~/.config/ai/memory/chatgpt/INDEX.md`, then read the matching topic file under `~/.config/ai/memory/chatgpt/knowledge/`; search the full transcripts with `rg -i "<keyword>" ~/.config/ai/memory/chatgpt/transcripts/`
Do not preemptively load all task-specific files. Load only the files relevant to the current task.

View File

@@ -0,0 +1,522 @@
{
"685167c3-b12c-800c-81d5-f6bdc8a74562": {
"file": "2025-06-17-programmazione-di-sistema.md",
"title": "Programmazione di Sistema",
"created": 1750165443.881027,
"update_time": 1780433040.853008,
"messages": 236,
"chars": 257690
},
"6866c486-7300-800c-be99-ac3501bf5b77": {
"file": "2025-07-03-linux-kernel-development.md",
"title": "Linux Kernel Development",
"created": 1751565446.622864,
"update_time": 1778923109.243077,
"messages": 8,
"chars": 13550
},
"686d38ec-32c4-800c-a985-c33dd4b44161": {
"file": "2025-07-08-elevazione-privilegi-con-script.md",
"title": "Elevazione privilegi con script",
"created": 1751988460.421606,
"update_time": 1752003606.28604,
"messages": 10,
"chars": 14403
},
"686d7d88-4460-800c-aa07-6c8f911f8c49": {
"file": "2025-07-08-setup-sviluppo-kernel-linux.md",
"title": "Setup sviluppo kernel Linux",
"created": 1752006024.448284,
"update_time": 1757349193.843844,
"messages": 22,
"chars": 30007
},
"686d81d8-69a4-800c-b1ba-530150987032": {
"file": "2025-07-08-tiling-wm-vs-de.md",
"title": "Tiling WM vs DE",
"created": 1752007128.639016,
"update_time": 1752651719.565563,
"messages": 112,
"chars": 144738
},
"686ff063-7428-800c-9016-e5aa61caea8e": {
"file": "2025-07-10-linguaggi-scripting-sistema.md",
"title": "Linguaggi scripting sistema",
"created": 1752166499.757389,
"update_time": 1780433158.417545,
"messages": 90,
"chars": 151683
},
"6874a63d-d6a0-800c-992f-cfc19f80454b": {
"file": "2025-07-14-distribuzioni-linux-piu-unix.md",
"title": "Distribuzioni Linux più UNIX",
"created": 1752475197.986237,
"update_time": 1752651704.598057,
"messages": 48,
"chars": 76857
},
"687bc9a4-1854-800c-ae29-716738d317e1": {
"file": "2025-07-19-workflow-sviluppo-unix.md",
"title": "Workflow sviluppo UNIX",
"created": 1752943012.277641,
"update_time": 1778923094.265412,
"messages": 104,
"chars": 122812
},
"68923cad-2cd4-832d-a105-614b03ca137e": {
"file": "2025-08-05-vantaggi-di-neomutt.md",
"title": "Vantaggi di NeoMutt",
"created": 1754414255.683661,
"update_time": 1755117969.032211,
"messages": 42,
"chars": 63147
},
"68bafb5a-d928-832a-8823-c593678fdf77": {
"file": "2025-09-05-task-emacs-coverage.md",
"title": "Task Emacs coverage",
"created": 1757084540.381688,
"update_time": 1757349203.215213,
"messages": 6,
"chars": 11719
},
"68bb674f-9908-8333-9173-93b9f68dc596": {
"file": "2025-09-06-emacs-per-sviluppo-kernel.md",
"title": "Emacs per sviluppo kernel",
"created": 1757112147.537248,
"update_time": 1765579118.250868,
"messages": 6,
"chars": 8762
},
"68cad26e-dd94-8324-8582-035e3ce3fc27": {
"file": "2025-09-17-sistema-operativo.md",
"title": "Sistema operativo",
"created": 1758122688.268689,
"update_time": 1772616989.003913,
"messages": 304,
"chars": 391155
},
"68cbae4c-c880-8330-b670-1ae2b72ecf3a": {
"file": "2025-09-18-rendere-email-piu-formale.md",
"title": "Rendere email più formale",
"created": 1758178908.385121,
"update_time": 1758179016.783481,
"messages": 2,
"chars": 1476
},
"6932aed3-5008-8325-b969-08dc6f35d7eb": {
"file": "2025-12-05-convertire-vmdk-in-qcow2.md",
"title": "Convertire VMDK in QCOW2",
"created": 1764929385.941481,
"update_time": 1764947756.940428,
"messages": 12,
"chars": 32301
},
"6932dbf4-7a64-832d-a7f7-5005245cf511": {
"file": "2025-12-05-come-posso-ottimizzare-la-risoluzione-di-una-macchina-virtua.md",
"title": "Come posso ottimizzare la risoluzione di una macchina virtuale su KVM/...",
"created": 1764940791.061897,
"update_time": 1764940820.249017,
"messages": 2,
"chars": 3973
},
"693c9a44-0b58-8328-afe4-c100001d0b74": {
"file": "2025-12-12-ottimizzazione-configurazione-emacs.md",
"title": "Ottimizzazione configurazione Emacs",
"created": 1765579333.840026,
"update_time": 1768033876.668465,
"messages": 124,
"chars": 443924
},
"69402abc-8e94-8330-8fbb-dd89e8500455": {
"file": "2025-12-15-configurazione-lsp-bash.md",
"title": "Configurazione LSP Bash",
"created": 1765812926.224716,
"update_time": 1765827941.712685,
"messages": 4,
"chars": 5448
},
"6941cf18-6f08-8329-b85e-fe8452eca316": {
"file": "2025-12-16-configurazione-go-incompleta.md",
"title": "Configurazione Go incompleta",
"created": 1765920538.129839,
"update_time": 1766521390.157466,
"messages": 74,
"chars": 238971
},
"6943c84b-4700-8326-b849-3f04db1095f0": {
"file": "2025-12-18-audio-remoto-con-rdp.md",
"title": "Audio remoto con RDP",
"created": 1766049983.358997,
"update_time": 1766056415.975342,
"messages": 18,
"chars": 22755
},
"6949436f-8188-8332-825a-5a1c110f979b": {
"file": "2025-12-22-modularizzare-configurazione-emacs.md",
"title": "Modularizzare configurazione Emacs",
"created": 1766409121.795851,
"update_time": 1766481588.378852,
"messages": 10,
"chars": 21994
},
"694a6621-433c-8332-bc9e-e30a7c1c58ff": {
"file": "2025-12-23-load-moduli-dichiarativo-emacs.md",
"title": "Load moduli dichiarativo Emacs",
"created": 1766483570.221675,
"update_time": 1766501505.279918,
"messages": 24,
"chars": 80230
},
"694fe73f-0098-8328-9f6c-5b741ff646f7": {
"file": "2025-12-27-dashboard-stile-doom.md",
"title": "Dashboard stile Doom",
"created": 1766844233.678888,
"update_time": 1766844282.338716,
"messages": 2,
"chars": 2899
},
"696a9898-b0f0-832d-9a3d-8fa63b04faae": {
"file": "2026-01-16-sistemi-bsd-per-laptop.md",
"title": "Sistemi BSD per laptop",
"created": 1768593690.929326,
"update_time": 1769535774.84958,
"messages": 48,
"chars": 82703
},
"69763d15-3e24-832c-9930-82efa6e25328": {
"file": "2026-01-25-shell-piu-usate-bsd.md",
"title": "Shell più usate BSD",
"created": 1769356579.54035,
"update_time": 1769535772.281699,
"messages": 4,
"chars": 5484
},
"6977b78a-f834-8331-82b9-4e2d54d812bf": {
"file": "2026-01-26-font-unix-simili-nerd.md",
"title": "Font UNIX simili Nerd",
"created": 1769453481.113524,
"update_time": 1769634405.491939,
"messages": 44,
"chars": 45673
},
"6978f931-c360-8330-bdca-e834d697e573": {
"file": "2026-01-27-suggerimenti-per-un-goal.md",
"title": "Suggerimenti per un goal",
"created": 1769535817.086813,
"update_time": 1770155923.725881,
"messages": 28,
"chars": 52098
},
"6979389b-b960-8325-96e3-7b001e50ce7a": {
"file": "2026-01-27-review-configurazione-terminale-st.md",
"title": "Review configurazione terminale st",
"created": 1769552156.508548,
"update_time": 1769588061.881458,
"messages": 18,
"chars": 23940
},
"6979c732-61d0-832d-bd30-b315fe48a404": {
"file": "2026-01-28-separazione-core-system-user.md",
"title": "Separazione core system user",
"created": 1769588543.151558,
"update_time": 1769589281.670914,
"messages": 4,
"chars": 5779
},
"6979d453-6280-8394-b226-f474e9f6396d": {
"file": "2026-01-28-review-configurazione-dmenu.md",
"title": "Review configurazione dmenu",
"created": 1769592007.552216,
"update_time": 1769592026.220427,
"messages": 2,
"chars": 1935
},
"6979d80a-94ec-8332-b457-8f9e0565fd50": {
"file": "2026-01-28-configurazione-ssh-e-gpg.md",
"title": "Configurazione SSH e GPG",
"created": 1769592846.117937,
"update_time": 1769594005.602308,
"messages": 4,
"chars": 4382
},
"697a3192-f26c-8332-84a0-efabc00bd9ca": {
"file": "2026-01-28-patch-consigliate-dwm.md",
"title": "Patch consigliate DWM",
"created": 1769615863.846342,
"update_time": 1769638385.348066,
"messages": 38,
"chars": 64134
},
"697a8a96-c698-8331-a69e-89e369ccf7af": {
"file": "2026-01-28-sistema-di-notifiche-linux.md",
"title": "Sistema di notifiche Linux",
"created": 1769638553.219296,
"update_time": 1769638664.930514,
"messages": 2,
"chars": 1656
},
"697a8d2b-4860-832d-b27a-afe1bc57a374": {
"file": "2026-01-28-configurazione-dwmblocks.md",
"title": "Configurazione dwmblocks",
"created": 1769639256.846482,
"update_time": 1769763606.585632,
"messages": 34,
"chars": 37666
},
"697b93aa-5540-8326-af88-8f1f7d3ec3dd": {
"file": "2026-01-29-troubleshooting-freebsd-firewall.md",
"title": "Troubleshooting FreeBSD Firewall",
"created": 1769706540.748549,
"update_time": 1769707710.068735,
"messages": 8,
"chars": 13624
},
"697b9bfb-517c-8329-84c7-b7e31f6064eb": {
"file": "2026-01-29-configurare-clipboard-con-dmenu.md",
"title": "Configurare clipboard con dmenu",
"created": 1769708566.139626,
"update_time": 1769710121.720131,
"messages": 10,
"chars": 12571
},
"697c8177-058c-832f-aa73-5d596937b859": {
"file": "2026-01-30-errore-compilazione-slstatus.md",
"title": "Errore compilazione slstatus",
"created": 1769767317.532827,
"update_time": 1769768704.260967,
"messages": 6,
"chars": 6210
},
"697cd843-9ebc-8330-8f76-8be9a5fc5b19": {
"file": "2026-01-30-migrazione-x11-a-xlibre.md",
"title": "Migrazione X11 a XLibre",
"created": 1769789535.046261,
"update_time": 1769789728.874143,
"messages": 4,
"chars": 6087
},
"69a7607d-5e54-8394-ac56-e8fed40dcbcf": {
"file": "2026-03-03-configurazione-nixos-da-fedora.md",
"title": "Configurazione NixOS da Fedora",
"created": 1772576934.83193,
"update_time": 1772577121.688374,
"messages": 2,
"chars": 13065
},
"69a8777f-9f50-8392-9cee-b97f215b50ce": {
"file": "2026-03-04-void-linux-install-script.md",
"title": "Void Linux install script",
"created": 1772648424.497395,
"update_time": 1773143444.063749,
"messages": 22,
"chars": 29459
},
"69a98a38-a190-8388-ad12-872cb1b5af6b": {
"file": "2026-03-05-differenze-tra-vi-e-vim.md",
"title": "Differenze tra vi e vim",
"created": 1772718693.477165,
"update_time": 1773143441.163061,
"messages": 42,
"chars": 130448
},
"69a9c38b-afe0-8385-b4d7-fedba0df178c": {
"file": "2026-03-05-configurazione-hyprland-all-black.md",
"title": "Configurazione Hyprland All-Black",
"created": 1772733451.019131,
"update_time": 1773143437.941349,
"messages": 32,
"chars": 71004
},
"69ab3ef4-39f4-8394-b777-d4f9b49ff0da": {
"file": "2026-03-06-configurazione-i3.md",
"title": "Configurazione i3",
"created": 1772830664.04396,
"update_time": 1773784658.530316,
"messages": 248,
"chars": 394245
},
"69b5da0f-d374-8389-9991-89a66fa1e673": {
"file": "2026-03-14-flatpak-con-i3.md",
"title": "Flatpak con i3",
"created": 1773525609.613291,
"update_time": 1773580920.053333,
"messages": 14,
"chars": 19985
},
"69b5dd63-7898-838a-94ee-b9743f50156b": {
"file": "2026-03-14-prompt-bash-personalizzato.md",
"title": "Prompt bash personalizzato",
"created": 1773526416.505007,
"update_time": 1773528489.873979,
"messages": 34,
"chars": 84255
},
"69cbefbd-4bb4-8384-a220-62384afef291": {
"file": "2026-03-31-progetti-sviluppati-insieme.md",
"title": "Progetti sviluppati insieme",
"created": 1774972909.115714,
"update_time": 1775227965.945387,
"messages": 36,
"chars": 89212
},
"69ff7592-2710-83eb-ae64-e5053372daef": {
"file": "2026-05-09-sviluppo-kernel-linux.md",
"title": "Sviluppo Kernel Linux",
"created": 1778349459.103319,
"update_time": 1778532066.320462,
"messages": 50,
"chars": 79051
},
"6a13661f-f078-83eb-8ee5-0c297c98db1e": {
"file": "2026-05-24-vim-vs-emacs.md",
"title": "Vim vs Emacs",
"created": 1779656226.660004,
"update_time": 1779656241.674157,
"messages": 4,
"chars": 1150
},
"6a1e6bf8-1b8c-8390-9833-994f3db7d912": {
"file": "2026-06-02-blocco-scrittura-dischi-esterni.md",
"title": "Blocco scrittura dischi esterni",
"created": 1780378678.612272,
"update_time": 1780378748.191027,
"messages": 4,
"chars": 4556
},
"6a1f410f-f820-8390-8a34-b6c737026d88": {
"file": "2026-06-02-studiare-xv6-con-apue.md",
"title": "Studiare xv6 con APUE",
"created": 1780433246.71313,
"update_time": 1780433260.971354,
"messages": 2,
"chars": 3033
},
"6a342e8f-c59c-83eb-9d0f-82d5dc067a98": {
"file": "2026-06-18-dual-boot-con-bitlocker.md",
"title": "Dual boot con BitLocker",
"created": 1781804806.225544,
"update_time": 1781805156.370825,
"messages": 8,
"chars": 9936
},
"6a380356-7dac-83eb-9098-1e5296fdb9d1": {
"file": "2026-06-21-skill-system-programmer.md",
"title": "Skill system programmer",
"created": 1782055831.553992,
"update_time": 1782059738.123604,
"messages": 18,
"chars": 42154
},
"6a3819f6-e77c-83eb-98dc-ac4b805343c3": {
"file": "2026-06-21-scelta-distro-linux-filosofia.md",
"title": "Scelta distro Linux filosofia",
"created": 1782061595.701426,
"update_time": 1782065360.547886,
"messages": 18,
"chars": 41421
},
"6a398d5f-7f94-83eb-b0ed-be540993bce5": {
"file": "2026-06-22-emacs-vs-terminal-workflow.md",
"title": "Emacs vs Terminal Workflow",
"created": 1782156772.747083,
"update_time": 1782160202.582969,
"messages": 16,
"chars": 29945
},
"6a39a298-6e90-83eb-9c95-f1e0399209f3": {
"file": "2026-06-22-stereotipi-vim-vs-emacs.md",
"title": "Stereotipi Vim vs Emacs",
"created": 1782162124.902723,
"update_time": 1787390859.164463,
"messages": 218,
"chars": 355733
},
"6a57b10f-61fc-83eb-aac9-c6f611262fac": {
"file": "2026-07-15-vim-vs-neovim.md",
"title": "Vim vs Neovim",
"created": 1784131859.552585,
"update_time": 1784667453.737104,
"messages": 52,
"chars": 82374
},
"6a5d3c43-0cb0-83eb-bba1-40fa22ac9294": {
"file": "2026-07-19-notifications-summary.md",
"title": "Notifications Summary",
"created": 1784495173.040645,
"update_time": 1784495180.502421,
"messages": 2,
"chars": 1177
},
"6a6c961b-c828-83eb-8b57-2bf590ca385e": {
"file": "2026-07-31-progetto-fsnap-per-apue.md",
"title": "Progetto fsnap per APUE",
"created": 1785501311.13758,
"update_time": 1786801580.813567,
"messages": 26,
"chars": 55637
},
"6a973c10-e46c-83eb-8628-6372ff91856d": {
"file": "2026-09-01-esportare-progetti-e-chat.md",
"title": "Esportare Progetti E Chat",
"created": 1788296240.486135,
"update_time": 1788296248.558538,
"messages": 2,
"chars": 1949
},
"6a9c77bc-3fe0-83ed-906d-19a089a7ac24": {
"file": "2026-09-05-risoluzione-nomi-locali-adguard.md",
"title": "Risoluzione Nomi Locali AdGuard",
"created": 1788639165.667587,
"update_time": 1788640495.337073,
"messages": 6,
"chars": 6731
},
"6aacdebe-cc08-83eb-a8bc-02affda0f2ca": {
"file": "2026-09-18-spiegare-passphrase-borg.md",
"title": "Spiegare passphrase Borg",
"created": 1789714111.294105,
"update_time": 1789715077.072826,
"messages": 7,
"chars": 11373
},
"6aad9e99-aa80-83eb-9f9d-9e0656b7fb2e": {
"file": "2026-09-18-monitoraggio-protezione-dati.md",
"title": "Monitoraggio protezione dati",
"created": 1789763226.739528,
"update_time": 1789763243.229647,
"messages": 1,
"chars": 4844
},
"6aad9ff4-f1bc-83eb-8ccb-561c5b870ce8": {
"file": "2026-09-18-test-di-ripristino-indipendenti.md",
"title": "Test di ripristino indipendenti",
"created": 1789763573.381085,
"update_time": 1789763585.105883,
"messages": 1,
"chars": 3134
},
"6ab1837e-8044-83ed-a832-40ea3c795642": {
"file": "2026-09-21-valutare-backup-borg.md",
"title": "Valutare backup Borg",
"created": 1790018431.185298,
"update_time": 1790019328.545161,
"messages": 11,
"chars": 13949
},
"6ab3fa9e-ed44-83eb-a8dc-156cf0aa4f67": {
"file": "2026-09-23-backup-usb-offline.md",
"title": "Backup USB offline",
"created": 1790179999.537027,
"update_time": 1790180017.108555,
"messages": 1,
"chars": 4627
},
"6ab4cb86-1dc0-83eb-b898-af3adde685bc": {
"file": "2026-09-24-monitoraggio-e-alert-atlas.md",
"title": "Monitoraggio E Alert Atlas",
"created": 1790233478.874482,
"update_time": 1790234352.43415,
"messages": 5,
"chars": 8976
}
}

View File

@@ -0,0 +1,76 @@
# ChatGPT Memory — Index
65 conversations imported from the official ChatGPT data export.
Structure: `transcripts/` (full active-branch transcripts), `knowledge/`
(distilled topic files), `assets/` (textual attachments only).
Search with ripgrep, e.g.:
rg -i "<keyword>" ~/.config/ai/memory/chatgpt/transcripts/
| Updated | Title | Topic | Messages | Chars | Transcript |
| --- | --- | --- | ---: | ---: | --- |
| 2026-09-24 | Monitoraggio E Alert Atlas | [tools-infra](knowledge/tools-infra.md) | 5 | 8976 | [transcript](transcripts/2026-09-24-monitoraggio-e-alert-atlas.md) |
| 2026-09-23 | Backup USB offline | [tools-infra](knowledge/tools-infra.md) | 1 | 4627 | [transcript](transcripts/2026-09-23-backup-usb-offline.md) |
| 2026-09-21 | Valutare backup Borg | [tools-infra](knowledge/tools-infra.md) | 11 | 13949 | [transcript](transcripts/2026-09-21-valutare-backup-borg.md) |
| 2026-09-18 | Test di ripristino indipendenti | [tools-infra](knowledge/tools-infra.md) | 1 | 3134 | [transcript](transcripts/2026-09-18-test-di-ripristino-indipendenti.md) |
| 2026-09-18 | Monitoraggio protezione dati | [tools-infra](knowledge/tools-infra.md) | 1 | 4844 | [transcript](transcripts/2026-09-18-monitoraggio-protezione-dati.md) |
| 2026-09-18 | Spiegare passphrase Borg | [tools-infra](knowledge/tools-infra.md) | 7 | 11373 | [transcript](transcripts/2026-09-18-spiegare-passphrase-borg.md) |
| 2026-09-05 | Risoluzione Nomi Locali AdGuard | [tools-infra](knowledge/tools-infra.md) | 6 | 6731 | [transcript](transcripts/2026-09-05-risoluzione-nomi-locali-adguard.md) |
| 2026-09-01 | Esportare Progetti E Chat | [workflow-progetti](knowledge/workflow-progetti.md) | 2 | 1949 | [transcript](transcripts/2026-09-01-esportare-progetti-e-chat.md) |
| 2026-08-15 | Progetto fsnap per APUE | [system-programming](knowledge/system-programming.md) | 26 | 55637 | [transcript](transcripts/2026-07-31-progetto-fsnap-per-apue.md) |
| 2026-07-19 | Notifications Summary | [dotfiles-wm](knowledge/dotfiles-wm.md) | 2 | 1177 | [transcript](transcripts/2026-07-19-notifications-summary.md) |
| 2026-07-21 | Vim vs Neovim | [editors](knowledge/editors.md) | 52 | 82374 | [transcript](transcripts/2026-07-15-vim-vs-neovim.md) |
| 2026-08-22 | Stereotipi Vim vs Emacs | [editors](knowledge/editors.md) | 218 | 355733 | [transcript](transcripts/2026-06-22-stereotipi-vim-vs-emacs.md) |
| 2026-06-22 | Emacs vs Terminal Workflow | [editors](knowledge/editors.md) | 16 | 29945 | [transcript](transcripts/2026-06-22-emacs-vs-terminal-workflow.md) |
| 2026-06-21 | Scelta distro Linux filosofia | [os-unix](knowledge/os-unix.md) | 18 | 41421 | [transcript](transcripts/2026-06-21-scelta-distro-linux-filosofia.md) |
| 2026-06-21 | Skill system programmer | [system-programming](knowledge/system-programming.md) | 18 | 42154 | [transcript](transcripts/2026-06-21-skill-system-programmer.md) |
| 2026-06-18 | Dual boot con BitLocker | [tools-infra](knowledge/tools-infra.md) | 8 | 9936 | [transcript](transcripts/2026-06-18-dual-boot-con-bitlocker.md) |
| 2026-06-02 | Studiare xv6 con APUE | [system-programming](knowledge/system-programming.md) | 2 | 3033 | [transcript](transcripts/2026-06-02-studiare-xv6-con-apue.md) |
| 2026-06-02 | Blocco scrittura dischi esterni | [tools-infra](knowledge/tools-infra.md) | 4 | 4556 | [transcript](transcripts/2026-06-02-blocco-scrittura-dischi-esterni.md) |
| 2026-05-24 | Vim vs Emacs | [editors](knowledge/editors.md) | 4 | 1150 | [transcript](transcripts/2026-05-24-vim-vs-emacs.md) |
| 2026-05-11 | Sviluppo Kernel Linux | [kernel-linux](knowledge/kernel-linux.md) | 50 | 79051 | [transcript](transcripts/2026-05-09-sviluppo-kernel-linux.md) |
| 2026-04-03 | Progetti sviluppati insieme | [workflow-progetti](knowledge/workflow-progetti.md) | 36 | 89212 | [transcript](transcripts/2026-03-31-progetti-sviluppati-insieme.md) |
| 2026-03-14 | Prompt bash personalizzato | [dotfiles-wm](knowledge/dotfiles-wm.md) | 34 | 84255 | [transcript](transcripts/2026-03-14-prompt-bash-personalizzato.md) |
| 2026-03-15 | Flatpak con i3 | [dotfiles-wm](knowledge/dotfiles-wm.md) | 14 | 19985 | [transcript](transcripts/2026-03-14-flatpak-con-i3.md) |
| 2026-03-17 | Configurazione i3 | [dotfiles-wm](knowledge/dotfiles-wm.md) | 248 | 394245 | [transcript](transcripts/2026-03-06-configurazione-i3.md) |
| 2026-03-10 | Configurazione Hyprland All-Black | [dotfiles-wm](knowledge/dotfiles-wm.md) | 32 | 71004 | [transcript](transcripts/2026-03-05-configurazione-hyprland-all-black.md) |
| 2026-03-10 | Differenze tra vi e vim | [editors](knowledge/editors.md) | 42 | 130448 | [transcript](transcripts/2026-03-05-differenze-tra-vi-e-vim.md) |
| 2026-03-10 | Void Linux install script | [os-unix](knowledge/os-unix.md) | 22 | 29459 | [transcript](transcripts/2026-03-04-void-linux-install-script.md) |
| 2026-03-03 | Configurazione NixOS da Fedora | [os-unix](knowledge/os-unix.md) | 2 | 13065 | [transcript](transcripts/2026-03-03-configurazione-nixos-da-fedora.md) |
| 2026-01-30 | Migrazione X11 a XLibre | [dotfiles-wm](knowledge/dotfiles-wm.md) | 4 | 6087 | [transcript](transcripts/2026-01-30-migrazione-x11-a-xlibre.md) |
| 2026-01-30 | Errore compilazione slstatus | [dotfiles-wm](knowledge/dotfiles-wm.md) | 6 | 6210 | [transcript](transcripts/2026-01-30-errore-compilazione-slstatus.md) |
| 2026-01-29 | Configurare clipboard con dmenu | [dotfiles-wm](knowledge/dotfiles-wm.md) | 10 | 12571 | [transcript](transcripts/2026-01-29-configurare-clipboard-con-dmenu.md) |
| 2026-01-29 | Troubleshooting FreeBSD Firewall | [os-unix](knowledge/os-unix.md) | 8 | 13624 | [transcript](transcripts/2026-01-29-troubleshooting-freebsd-firewall.md) |
| 2026-01-30 | Configurazione dwmblocks | [dotfiles-wm](knowledge/dotfiles-wm.md) | 34 | 37666 | [transcript](transcripts/2026-01-28-configurazione-dwmblocks.md) |
| 2026-01-28 | Sistema di notifiche Linux | [dotfiles-wm](knowledge/dotfiles-wm.md) | 2 | 1656 | [transcript](transcripts/2026-01-28-sistema-di-notifiche-linux.md) |
| 2026-01-28 | Patch consigliate DWM | [dotfiles-wm](knowledge/dotfiles-wm.md) | 38 | 64134 | [transcript](transcripts/2026-01-28-patch-consigliate-dwm.md) |
| 2026-01-28 | Configurazione SSH e GPG | [tools-infra](knowledge/tools-infra.md) | 4 | 4382 | [transcript](transcripts/2026-01-28-configurazione-ssh-e-gpg.md) |
| 2026-01-28 | Review configurazione dmenu | [dotfiles-wm](knowledge/dotfiles-wm.md) | 2 | 1935 | [transcript](transcripts/2026-01-28-review-configurazione-dmenu.md) |
| 2026-01-28 | Separazione core system user | [os-unix](knowledge/os-unix.md) | 4 | 5779 | [transcript](transcripts/2026-01-28-separazione-core-system-user.md) |
| 2026-01-28 | Review configurazione terminale st | [dotfiles-wm](knowledge/dotfiles-wm.md) | 18 | 23940 | [transcript](transcripts/2026-01-27-review-configurazione-terminale-st.md) |
| 2026-02-03 | Suggerimenti per un goal | [workflow-progetti](knowledge/workflow-progetti.md) | 28 | 52098 | [transcript](transcripts/2026-01-27-suggerimenti-per-un-goal.md) |
| 2026-01-28 | Font UNIX simili Nerd | [os-unix](knowledge/os-unix.md) | 44 | 45673 | [transcript](transcripts/2026-01-26-font-unix-simili-nerd.md) |
| 2026-01-27 | Shell più usate BSD | [os-unix](knowledge/os-unix.md) | 4 | 5484 | [transcript](transcripts/2026-01-25-shell-piu-usate-bsd.md) |
| 2026-01-27 | Sistemi BSD per laptop | [os-unix](knowledge/os-unix.md) | 48 | 82703 | [transcript](transcripts/2026-01-16-sistemi-bsd-per-laptop.md) |
| 2025-12-27 | Dashboard stile Doom | [emacs](knowledge/emacs.md) | 2 | 2899 | [transcript](transcripts/2025-12-27-dashboard-stile-doom.md) |
| 2025-12-23 | Load moduli dichiarativo Emacs | [emacs](knowledge/emacs.md) | 24 | 80230 | [transcript](transcripts/2025-12-23-load-moduli-dichiarativo-emacs.md) |
| 2025-12-23 | Modularizzare configurazione Emacs | [emacs](knowledge/emacs.md) | 10 | 21994 | [transcript](transcripts/2025-12-22-modularizzare-configurazione-emacs.md) |
| 2025-12-18 | Audio remoto con RDP | [tools-infra](knowledge/tools-infra.md) | 18 | 22755 | [transcript](transcripts/2025-12-18-audio-remoto-con-rdp.md) |
| 2025-12-23 | Configurazione Go incompleta | [languages](knowledge/languages.md) | 74 | 238971 | [transcript](transcripts/2025-12-16-configurazione-go-incompleta.md) |
| 2025-12-15 | Configurazione LSP Bash | [emacs](knowledge/emacs.md) | 4 | 5448 | [transcript](transcripts/2025-12-15-configurazione-lsp-bash.md) |
| 2026-01-10 | Ottimizzazione configurazione Emacs | [emacs](knowledge/emacs.md) | 124 | 443924 | [transcript](transcripts/2025-12-12-ottimizzazione-configurazione-emacs.md) |
| 2025-12-05 | Come posso ottimizzare la risoluzione di una macchina virtuale su KVM/... | [tools-infra](knowledge/tools-infra.md) | 2 | 3973 | [transcript](transcripts/2025-12-05-come-posso-ottimizzare-la-risoluzione-di-una-macchina-virtua.md) |
| 2025-12-05 | Convertire VMDK in QCOW2 | [tools-infra](knowledge/tools-infra.md) | 12 | 32301 | [transcript](transcripts/2025-12-05-convertire-vmdk-in-qcow2.md) |
| 2025-09-18 | Rendere email più formale | [workflow-progetti](knowledge/workflow-progetti.md) | 2 | 1476 | [transcript](transcripts/2025-09-18-rendere-email-piu-formale.md) |
| 2026-03-04 | Sistema operativo | [os-unix](knowledge/os-unix.md) | 304 | 391155 | [transcript](transcripts/2025-09-17-sistema-operativo.md) |
| 2025-12-12 | Emacs per sviluppo kernel | [emacs](knowledge/emacs.md) | 6 | 8762 | [transcript](transcripts/2025-09-06-emacs-per-sviluppo-kernel.md) |
| 2025-09-08 | Task Emacs coverage | [emacs](knowledge/emacs.md) | 6 | 11719 | [transcript](transcripts/2025-09-05-task-emacs-coverage.md) |
| 2025-08-13 | Vantaggi di NeoMutt | [workflow-progetti](knowledge/workflow-progetti.md) | 42 | 63147 | [transcript](transcripts/2025-08-05-vantaggi-di-neomutt.md) |
| 2026-05-16 | Workflow sviluppo UNIX | [workflow-progetti](knowledge/workflow-progetti.md) | 104 | 122812 | [transcript](transcripts/2025-07-19-workflow-sviluppo-unix.md) |
| 2025-07-16 | Distribuzioni Linux più UNIX | [os-unix](knowledge/os-unix.md) | 48 | 76857 | [transcript](transcripts/2025-07-14-distribuzioni-linux-piu-unix.md) |
| 2026-06-02 | Linguaggi scripting sistema | [languages](knowledge/languages.md) | 90 | 151683 | [transcript](transcripts/2025-07-10-linguaggi-scripting-sistema.md) |
| 2025-07-16 | Tiling WM vs DE | [dotfiles-wm](knowledge/dotfiles-wm.md) | 112 | 144738 | [transcript](transcripts/2025-07-08-tiling-wm-vs-de.md) |
| 2025-09-08 | Setup sviluppo kernel Linux | [kernel-linux](knowledge/kernel-linux.md) | 22 | 30007 | [transcript](transcripts/2025-07-08-setup-sviluppo-kernel-linux.md) |
| 2025-07-08 | Elevazione privilegi con script | [system-programming](knowledge/system-programming.md) | 10 | 14403 | [transcript](transcripts/2025-07-08-elevazione-privilegi-con-script.md) |
| 2026-05-16 | Linux Kernel Development | [kernel-linux](knowledge/kernel-linux.md) | 8 | 13550 | [transcript](transcripts/2025-07-03-linux-kernel-development.md) |
| 2026-06-02 | Programmazione di Sistema | [system-programming](knowledge/system-programming.md) | 236 | 257690 | [transcript](transcripts/2025-06-17-programmazione-di-sistema.md) |

View File

@@ -0,0 +1,8 @@
# Pending distillation
Conversations not yet distilled into `knowledge/` topic files, most
valuable first. After distilling, record the mapping in
`knowledge/.distilled.json` and re-run
`scripts/chatgpt_export_to_memory.py` to refresh this queue.
Nothing pending: every conversation has a knowledge topic.

View File

@@ -0,0 +1,11 @@
# Assets
Binary and personal assets (PDFs, images) are deliberately not
imported into the memory tree; they remain only in the original export.
| Name | Kind | Size | Origin conversation | Action |
| --- | --- | ---: | --- | --- |
| Confronto tra notifiche Dunst e Mako.png | missing | — | Tiling WM vs DE | not present in this export |
| Scrivania Linux con tema Catppuccin Frappe.png | missing | — | Tiling WM vs DE | not present in this export |
| correlazione_sistemi_operativi_apue.org | text | 12128 | 69f7d35d-4978-838b-bcc6-b8c3c68abe36 | copied |
| ec021735-83cc-4e2c-998b-38c64e2833c9.png | binary | 284086 | Stereotipi Vim vs Emacs | listed only (privacy) |

View File

@@ -0,0 +1,114 @@
#+TITLE: Correlazione tra Sistemi Operativi - Concetti ed esempi, 8ª ed. e APUE
#+AUTHOR: Fabio Scotto di Santolo
#+LANGUAGE: it
#+OPTIONS: toc:2 num:nil
* Nota
Questa tabella mette in relazione i capitoli di /Sistemi Operativi - Concetti ed esempi/, 8ª edizione, di Silberschatz, Galvin e Gagne, con i capitoli di /Advanced Programming in the UNIX Environment/ (APUE), 3ª edizione, di Stevens e Rago.
L'obiettivo non è sostituire nessuno dei due testi, ma usarli insieme:
- *Sistemi Operativi* fornisce il modello teorico: processi, memoria, file system, scheduling, sincronizzazione, I/O.
- *APUE* mostra come quei concetti emergono concretamente nelle API UNIX/POSIX.
* Tabella di correlazione
| Capitolo Sistemi Operativi, 8ª ed. | Tema teorico | Capitoli APUE correlati | API / argomenti APUE | Priorità per APUE | Note di studio |
|------------------------------------+--------------+--------------------------+----------------------+-------------------+----------------|
| Cap. 1 - Introduzione | Ruolo del sistema operativo, kernel, astrazioni, protezione, interrupt, system call | Cap. 1 - UNIX System Overview; Cap. 2 - UNIX Standardization and Implementations | architettura UNIX, kernel, shell, standard POSIX, system call, librerie | Alta | Da leggere prima di APUE per avere il lessico base: kernel, user mode, system call, processo, file. |
| Cap. 2 - Strutture dei sistemi operativi | Servizi OS, interfacce, system call, struttura kernel, macchine virtuali | Cap. 1; Cap. 2; Cap. 3 - File I/O | syscall vs funzioni di libreria, POSIX, primitive UNIX | Alta | Aiuta a capire perché APUE distingue spesso tra interfaccia standard, implementazione e comportamento specifico del sistema. |
| Cap. 3 - Processi | Processo, PCB, stati, context switch, creazione/terminazione, IPC base | Cap. 7 - Process Environment; Cap. 8 - Process Control; Cap. 9 - Process Relationships; Cap. 15 - Interprocess Communication | =fork()=, =exec()=, =wait()=, exit status, environment, pipe, FIFO | Fondamentale | È il ponte più importante: APUE diventa molto più chiaro se hai già il modello teorico di processo. |
| Cap. 4 - Thread | Thread, modelli user/kernel, multithreading, concorrenza nello stesso processo | Cap. 11 - Threads; Cap. 12 - Thread Control | =pthread_create()=, mutex, condition variable, thread attributes, cancellazione | Alta | APUE è molto pratico sui pthread; il capitolo teorico serve per capire condivisione di memoria, stack, race e scheduling. |
| Cap. 5 - Scheduling della CPU | Scheduler, processi ready/running/waiting, algoritmi FCFS/SJF/RR/priorità | Cap. 8; Cap. 9; Cap. 11 | ordine non deterministico tra processi/thread, =nice()=, priorità, timing | Media | Non serve conoscere tutti gli algoritmi per APUE, ma serve capire che l'ordine di esecuzione non è garantito. |
| Cap. 6 - Sincronizzazione dei processi | Race condition, sezione critica, mutex, semafori, monitor | Cap. 10 - Signals; Cap. 11; Cap. 12; Cap. 15 | signal safety, mutex, condition variable, semafori POSIX/System V, IPC | Fondamentale | Cruciale per scrivere codice robusto: segnali, thread e IPC senza modello di concorrenza diventano pericolosi. |
| Cap. 7 - Deadlock | Condizioni di deadlock, prevenzione, avoidance, rilevamento | Cap. 11; Cap. 12; Cap. 15; Cap. 17 - Advanced IPC | lock ordering, mutex multipli, file locking, record locking, IPC | Media | APUE non tratta il deadlock in modo teorico esteso, ma il concetto è essenziale quando usi lock e risorse condivise. |
| Cap. 8 - Memoria principale | Address space, linking/loading, paginazione, segmentazione, memoria virtuale di base | Cap. 7; Cap. 8; Cap. 14 - Advanced I/O | layout processo, stack, heap, =fork()=, =exec()=, =mmap()= | Alta | Serve per capire cosa viene ereditato dopo =fork()=, cosa cambia con =exec()= e perché la memoria del processo è un'astrazione. |
| Cap. 9 - Memoria virtuale | Demand paging, copy-on-write, page replacement, mmap concettuale | Cap. 7; Cap. 8; Cap. 14 | copy-on-write dopo =fork()=, memory mapping, file mappati in memoria | Alta | Molto utile per non interpretare =fork()= come una copia fisica ingenua dell'intero processo. |
| Cap. 10 - Interfaccia del file system | File, directory, attributi, permessi, operazioni, link | Cap. 3 - File I/O; Cap. 4 - Files and Directories; Cap. 6 - System Data Files and Information | =open()=, =read()=, =write()=, =stat()=, =chmod()=, =link()=, =symlink()=, =opendir()= | Fondamentale | È il cuore dell'I/O UNIX: inode, directory, permessi e pathname spiegano moltissimo di APUE. |
| Cap. 11 - Implementazione del file system | Strutture interne, allocazione, free space, buffer cache, journaling | Cap. 3; Cap. 4; Cap. 5 - Standard I/O Library; Cap. 14 | buffer cache, sync, fsync, stdio buffering, performance I/O | Alta | Aiuta a capire differenza tra scrivere in un buffer utente, nella cache kernel e su disco fisico. |
| Cap. 12 - Struttura dei dispositivi di memoria di massa | Dischi, scheduling disco, blocchi, affidabilità | Cap. 3; Cap. 4; Cap. 14 | I/O sequenziale/casuale, blocchi, =lseek()=, performance, =fsync()= | Media | Utile soprattutto se studi performance I/O, filesystem e comportamento reale della persistenza. |
| Cap. 13 - Sistemi di I/O | Driver, interrupt, DMA, buffering, caching, blocking/non-blocking I/O | Cap. 3; Cap. 5; Cap. 14; Cap. 18 - Terminal I/O; Cap. 19 - Pseudo Terminals | =fcntl()=, nonblocking I/O, =select()=, =poll()=, terminal driver, pty | Alta | Spiega bene perché una =read()= può bloccare, essere interrotta, o comportarsi diversamente su file, terminali, pipe e socket. |
| Cap. 14 - Protezione | Domini di protezione, access control, capability, permessi | Cap. 4; Cap. 6; Cap. 7; Cap. 8 | UID/GID, effective UID, setuid, file permissions, =umask()= | Alta | Fondamentale per capire il modello di sicurezza UNIX: identità del processo più permessi del file. |
| Cap. 15 - Sicurezza | Minacce, autenticazione, attacchi, hardening | Cap. 4; Cap. 6; Cap. 8; Cap. 13 - Daemon Processes; Cap. 16 - Network IPC: Sockets | setuid, daemon, socket, permessi, ambiente, file temporanei | Media | APUE non è un libro di security, ma molte API UNIX sono pericolose se usate senza questo contesto. |
| Cap. 16 - Strutture dei sistemi distribuiti | Sistemi distribuiti, comunicazione, modelli client/server | Cap. 16; Cap. 17 | socket, client/server, descriptor passing, IPC avanzata | Media | Utile quando passi dalla programmazione locale a processi che comunicano via rete. |
| Cap. 17 - File system distribuiti | File remoti, naming, caching, coerenza | Cap. 3; Cap. 4; Cap. 14; Cap. 16 | semantica file su NFS/remote FS, errori I/O, locking, caching | Bassa/Media | Non è indispensabile all'inizio, ma spiega perché non tutti i filesystem rispettano esattamente le stesse assunzioni. |
| Cap. 18 - Coordinamento distribuito | Ordinamento eventi, mutua esclusione distribuita, recovery | Cap. 15; Cap. 16; Cap. 17 | IPC, socket, protocolli applicativi, sincronizzazione tra processi | Bassa | Utile solo se vuoi estendere APUE verso sistemi distribuiti o server complessi. |
| Cap. 19 - Sistemi real-time | Vincoli temporali, scheduling real-time, latenza | Cap. 8; Cap. 11; Cap. 12; Cap. 14 | scheduling, priorità, segnali, timer, I/O non bloccante | Bassa/Media | Interessante, ma non propedeutico alla maggior parte di APUE. |
| Cap. 20 - Sistemi multimediali | Scheduling e I/O per audio/video, continuità temporale | Cap. 14; Cap. 16 | I/O avanzato, buffering, rete, timing | Bassa | Poco centrale per APUE classico. |
| Cap. 21 - Il sistema Linux | Linux come caso di studio: processi, memoria, filesystem, moduli, I/O | Tutto APUE, in particolare Cap. 1, 3, 4, 7, 8, 10, 11, 14, 15, 16 | comportamento reale su Linux delle API UNIX/POSIX | Alta | Molto utile per collegare teoria, APUE e ambiente GNU/Linux reale. |
| Cap. 22 - Windows XP | Architettura Windows, processi, thread, memoria, I/O, sicurezza | Confronto indiretto con APUE | differenze rispetto a POSIX/UNIX | Bassa | Utile solo come confronto architetturale, non necessario per studiare APUE. |
| Cap. 23 - Sistemi operativi influenti | UNIX, BSD, Linux, Mach, altri sistemi storici | Cap. 1; Cap. 2 | contesto storico UNIX/POSIX/BSD/System V | Media | Aiuta a capire perché APUE cita spesso differenze storiche tra UNIX, BSD, System V e POSIX. |
* Percorso consigliato
** Prima passata: capitoli teorici davvero propedeutici ad APUE
Se vuoi leggere il minimo indispensabile prima o durante APUE, concentrati su:
| Priorità | Capitoli Sistemi Operativi | Perché |
|----------+----------------------------+--------|
| 1 | Cap. 1 - Introduzione | Lessico base: kernel, processi, system call, protezione. |
| 2 | Cap. 2 - Strutture dei sistemi operativi | Capire interfacce, servizi OS e ruolo delle syscall. |
| 3 | Cap. 3 - Processi | Necessario per =fork()=, =exec()=, =wait()=, zombie, orphan. |
| 4 | Cap. 8 - Memoria principale | Necessario per address space, stack, heap, ereditarietà dopo =fork()=. |
| 5 | Cap. 9 - Memoria virtuale | Necessario per copy-on-write e =mmap()=. |
| 6 | Cap. 10 - Interfaccia del file system | Necessario per file descriptor, directory, inode, link, permessi. |
| 7 | Cap. 13 - Sistemi di I/O | Necessario per blocking I/O, buffering, driver, terminali. |
| 8 | Cap. 6 - Sincronizzazione dei processi | Necessario per thread, segnali e IPC robusto. |
** Seconda passata: lettura APUE guidata dalla teoria
| Blocco APUE | Capitoli APUE | Teoria da affiancare |
|-------------+---------------+----------------------|
| Fondamenti UNIX | APUE 1-2 | Sistemi Operativi 1-2, 23 |
| File e directory | APUE 3-5 | Sistemi Operativi 10-13 |
| Ambiente di processo | APUE 6-7 | Sistemi Operativi 1-3, 8 |
| Processi | APUE 8-9 | Sistemi Operativi 3, 5, 8, 9 |
| Segnali | APUE 10 | Sistemi Operativi 3, 6, 13 |
| Thread | APUE 11-12 | Sistemi Operativi 4, 5, 6, 7 |
| Daemon | APUE 13 | Sistemi Operativi 3, 14, 15 |
| I/O avanzato | APUE 14 | Sistemi Operativi 11-13 |
| IPC | APUE 15, 17 | Sistemi Operativi 3, 6, 7, 16, 18 |
| Socket | APUE 16 | Sistemi Operativi 16 |
| Terminali | APUE 18-19 | Sistemi Operativi 13 |
* Lettura pratica consigliata
** Metodo
Per ogni argomento APUE, fai questo ciclo:
1. Leggi il capitolo APUE.
2. Torna al capitolo teorico corrispondente di /Sistemi Operativi/.
3. Scrivi un piccolo programma C che dimostri il comportamento.
4. Osserva con strumenti come =strace=, =lsof=, =ps=, =pstree=, =top=, =gdb=.
** Esempi concreti
| Tema | Teoria | APUE | Esperimento C |
|------+--------+------+---------------|
| =fork()= | Processi + memoria virtuale | APUE 8 | Modifica una variabile dopo =fork()= e osserva che padre e figlio non condividono lo stesso valore. |
| Buffering | I/O + file system implementation | APUE 5 | Usa =printf()= prima di =fork()= e confronta con =write()=. |
| File descriptor | File system + I/O | APUE 3-4 | Apri un file, fai =fork()=, scrivi da padre e figlio, osserva offset condiviso. |
| Zombie | Process lifecycle | APUE 8 | Crea un figlio che termina senza =wait()= e osserva con =ps=. |
| Pipe | IPC | APUE 15 | Implementa =ls | wc -l= con =pipe()=, =fork()=, =dup2()=, =execvp()=. |
| Signal safety | Sincronizzazione + interrupt | APUE 10 | Gestisci =SIGINT= usando =sigaction()= e solo funzioni async-signal-safe. |
| Thread race | Thread + sincronizzazione | APUE 11-12 | Incrementa un contatore condiviso con e senza mutex. |
| mmap | Memoria virtuale + I/O | APUE 14 | Mappa un file in memoria e modifica il contenuto tramite puntatore. |
* Sintesi operativa
Per capire bene APUE, i capitoli più propedeutici di /Sistemi Operativi - Concetti ed esempi/ sono:
1. Cap. 1 - Introduzione
2. Cap. 2 - Strutture dei sistemi operativi
3. Cap. 3 - Processi
4. Cap. 4 - Thread
5. Cap. 6 - Sincronizzazione dei processi
6. Cap. 8 - Memoria principale
7. Cap. 9 - Memoria virtuale
8. Cap. 10 - Interfaccia del file system
9. Cap. 11 - Implementazione del file system
10. Cap. 13 - Sistemi di I/O
11. Cap. 14 - Protezione
Il resto è utile, ma può essere letto dopo o solo quando APUE porta naturalmente verso quei temi.

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