Definitive guide for AI agents (and human contributors) working on the refugiOS codebase. Read this first before making any change.
refugiOS is a portable, offline-first Linux operating system designed as a "digital refuge" for emergency and personal-resilience scenarios. It boots from a USB on any PC or Raspberry Pi and carries offline Wikipedia, world maps, a private local AI (LLM), LUKS-encrypted personal vaults, and survival guides — all working with zero Internet dependency.
- Paradigm: "Prepare it today at home, use it when there's no Internet."
- Distribution model: A lightweight base image (~16 GB) is distributed; the user runs the installer once while online to download exactly the content they need (Wikipedia tier, AI model, maps, etc.). After that, the device operates 100% offline.
- License: GNU AGPL-3.0 (
LICENSE). - Status: First Beta, actively developed.
- Current version:
0.29(seeCHANGELOG.md). Versioning follows Semantic Versioning; the changelog follows Keep a Changelog. - Repository:
https://github.com/Ganso/refugiOS.git(branchmain). - Primary language of maintainers: Spanish — but all code, comments, variable
names, commit messages, and logic MUST be in English (see
CONTRIBUTING.md). User-facing strings and documentation are bilingual (ES + EN).
refugiOS/
├── AGENTS.md # This file
├── CHANGELOG.md # Version history (Keep a Changelog, written in Spanish)
├── CONTRIBUTING.md # Bilingual EN/ES contributing guidelines
├── LICENSE # AGPL-3.0 full text
├── README.md # Primary README (Spanish)
├── README.en.md # English README (mirror)
├── build_all.sh # Convenience: builds ES + EN images, cleans logs
├── install.py # MAIN installer — dialog-based TUI wizard (~1490 lines)
├── install.sh # Bash bootstrapper (downloads + launches install.py)
├── i18n.py # Python localization system (EN/ES dictionary + T())
├── doc/ # 26 bilingual .md docs (GitHub Wiki source)
├── media/ # Branding + screenshots (see media/README.md)
│ ├── logo/ # refugiOS.png, .ai, .pdf, fondo.png (wallpaper)
│ └── screenshots/ # Application screenshots, ES + EN
└── scripts/ # Helper / runtime / build / test scripts
├── build_refugios.sh # Image builder (debootstrap Debian Trixie + XFCE)
├── i18n.sh # Bash localization system (parallel to i18n.py)
├── refugios-ai-selector.sh # AI model selector + Llamafile launcher
├── refugios-kiwix.sh # Kiwix/ZIM launcher (AppImage/Flatpak/binary)
├── refugios-maps.sh # Organic Maps launcher (RPi software-rendering hack)
├── refugios-vault.py # LUKS vault manager (create/open/close/delete, TUI)
└── test_boot.sh # QEMU UEFI boot test for generated images
└── tests/ # Automated test suite (docs: doc/Test-Suite-EN.md)
├── README.md # Pointer to the bilingual guides in doc/
├── run_all.sh # Whole suite; --quick skips anything needing Docker
├── run_in_container.sh # Runs a command in the privileged Debian container
├── docker/Dockerfile # Test container (debootstrap, cryptsetup, shellcheck...)
├── lint.sh # bash -n + py_compile (+ shellcheck when available)
├── unit_bash.sh # i18n precedence, launchers, test_boot.sh arguments
├── unit_install.py # install.py internals (downloads, dialog, exit code...)
├── test_install_sh.sh # Bootstrapper: Developer Mode and validations
├── test_vault.sh # Real LUKS vaults: password verification + full cycle
├── test_build.sh # Real image build aborted on purpose inside the chroot
├── luks_pty.py # Drives cryptsetup over a real terminal
├── qemu_boot_check.py # Headless boot + screenshots at given moments
├── qemu_ctl.py # Controls a running VM (keys, text, clicks, screenshots)
└── prepare_e2e_image.sh # Injects the local repo into an image for an E2E run
There is no package.json, requirements.txt, Makefile, pyproject.toml,
setup.py, .github/workflows/, CI configuration, .opencode/, opencode.json, or
CLAUDE.md. Python dependencies are declared inline in install.sh /
build_refugios.sh and installed via apt at runtime.
There is an automated test suite under tests/ (plain unittest + Bash, no test
framework to install), but no CI: nothing runs it automatically, so run
bash tests/run_all.sh yourself before proposing changes. Whatever needs root runs in a
privileged Docker container, so sudo is never required. Read doc/Test-Suite-EN.md first.
.gitignore protects: Python bytecode (__pycache__/), virtualenvs, OS metadata,
editor configs, and refugiOS-specific large binaries — *.zim, *.gguf, *.img,
*.appimage, *.torrent, refugios_vars.fd, *.log, scripts/*.log. A multi-GB
refugios-base-*.img and refugios_vars.fd may exist locally for testing; never
commit them.
- Pre-built image: Debian Trixie + XFCE, natively installed (not a Live system).
- Alternative: Xubuntu LTS (24.04) or 25.10 Minimal, Live mode with persistence (BIOS/MBR-compatible path).
- Desktop environment: XFCE (low resource use; fresh boot < 1 GB RAM). On Raspberry Pi: Raspberry Pi OS with PCManFM/LightDM.
- Display server: Both X11 and Wayland supported; detected via
$XDG_SESSION_TYPE.
- PC (x86_64): Any Intel/AMD PC (64-bit), boots from USB via both UEFI and Legacy BIOS (hybrid GPT with BIOS boot partition). Uses AppImages + Flatpaks + APT.
- Raspberry Pi (ARM): Certified on RPi 3B+ (1 GB RAM) with Raspberry Pi OS
64-bit. RPi 4/5 and Zero 2W theoretically functional but untested. The installer
auto-detects ARM via
/proc/device-tree/modeland switches to native APT packages; Organic Maps is forced to software rendering on RPi 1/2/3/Zero (no OpenGL ES 3.0).
~/refugiOS/
├── Apps/versions/ # AppImage binaries (versioned, dated filenames)
├── Knowledge/versions/ # ZIM files (versioned, dated filenames)
├── AI/versions/ # GGUF model files + llamafile binary (versioned)
├── Vaults/ # LUKS vault container files (*.img)
└── Scripts/ # Deployed helper scripts + i18n.py + i18n.sh
sync_resources() in install.py symlinks the best (latest) versioned file in each
versions/ dir to a stable name at the parent level (e.g. Knowledge/wikipedia.zim,
AI/llamafile, AI/<tier>-model.gguf). Desktop launchers reference the stable
symlinks. Wikipedia, WikiMed and WikiHow get a launcher on the desktop itself; every
other book gets its launcher in a desktop folder named after the i18n key
library_folder ("Biblioteca refugiOS" / "refugiOS Library").
Offline maps live where the Organic Maps Flatpak reads them:
~/.var/app/app.organicmaps.desktop/data/OMaps/<data version>/<Region>.mwm (newer
releases rename OMaps to OrganicMaps; the installer uses whichever exists).
Desktop directory is auto-detected as ~/Desktop or ~/Escritorio (Spanish locale).
Generates a base refugiOS disk image from scratch via debootstrap.
- Must run as root. Host must be Debian-based (debian|ubuntu|mint|pop), amd64.
- Options:
-s SIZE(default16G; format<num>[GMK]),-l LANG(es|en, defaultes). - Output:
refugios-base-<SIZE>-<LANG>.img(sparse file). - Flow: validate → install host deps (
debootstrap parted dosfstools e2fsprogs) →truncatesparse image → GPT partition (BIOS_BOOT 1MiB, EFI FAT32 514MiB ESP, ROOT ext4) →losetup -Pf→ format → mount →debootstrap --arch=amd64 trixie→ generate/etc/fstabwith real UUIDs → chroot: APT sources (main/contrib/non-free), install kernel + GRUB + XFCE + lightdm + firmware (iwlwifi, brcm, atheros, amd)- offline installer tools (python3, dialog, aria2, jq, rsync) + flatpak, set locale/keyboard, install GRUB both UEFI-removable
(
--removable --no-nvram) and BIOS-MBR, createrefugiosuser (passwordless sudo, LightDM autologin, screenlock disabled).
- offline installer tools (python3, dialog, aria2, jq, rsync) + flatpak, set locale/keyboard, install GRUB both UEFI-removable
(
trap cleanup EXITrobustly unmounts/detaches on any exit.- Full output tee'd to
scripts/build_refugios_<timestamp>.log(gitignored). - All injected user-facing strings are localized at build time (es/en branches set ~30 variables).
| Injected path | Purpose |
|---|---|
/usr/local/bin/refugios-expand.sh + .service |
First-boot auto-grow of root partition via growpart+resize2fs; self-disabling after one run. |
/usr/local/bin/refugios-install-wrapper.sh |
Connectivity check (ping github.com) + launches installer; zenity/console fallback if offline. Also recreated by install.py (ensure_install_icon). |
/usr/local/bin/refugios-trust-launcher.sh + autostart |
Marks .desktop files as XFCE-trusted via gio set metadata::xfce-exe-checksum (SHA-256). |
/usr/local/bin/refugios-welcome.sh + autostart |
First-boot zenity welcome popup showing disk size; guarded by ~/.refugios-welcome-done marker. |
Instalar_refugiOS.desktop (skel + user Desktop) |
"Complete refugiOS installation" launcher that re-runs the installer. |
Convenience wrapper: sudo ./scripts/build_refugios.sh -l es && sudo ./scripts/build_refugios.sh -l en && sudo rm -f ./scripts/*.log.
Boots a generated image in QEMU with UEFI (OVMF) to verify GRUB → LightDM autologin → XFCE desktop with installer launcher and welcome popup.
- Does NOT require root (unless KVM perms needed).
- Supports more host distros than
build_refugios.sh(Debian/Ubuntu/Mint/Pop/Fedora/ Arch/Manjaro/openSUSE). - Auto-finds
refugios-base-*.imgin workspace, or accepts a size arg. - Detects OVMF firmware across distro-specific paths; creates writable
refugios_vars.fdcopy; detects KVM (/dev/kvm); 8 GB RAM, 2 CPUs, virtio VGA, NAT. - Run:
bash scripts/test_boot.sh [-s SIZE] [-l LANG](the old positionaltest_boot.sh SIZEstill works; images are namedrefugios-base-SIZE-LANG.img). - RAM is derived from the host's available memory, clamped to [2G, 8G].
The core of the project. A dialog-based TUI wizard (~1490 lines). Must run as a
normal user (NOT root); uses sudo internally.
os, sys, subprocess, urllib.request/error/parse, json, hashlib, base64, shutil, re, time, random (stdlib) +
i18n (local) + dialog (python3-dialog, required).
Entries hold i18n keys (label_key, title_key), never translated text: the
module is imported before the user picks a language.
-
WIKIPEDIA_CONFIG— 5 tiers, smallest first:wiki_lite(top_mini),wiki_top_nopic,wiki_top_maxi,wiki_nopics(all_nopic),wiki_total(all_maxi). The preselected tier is the largest whose size fits inWIKI_SPACE_SHARE(35%) of the free space (default_wiki_index). -
LIBRARY_CATALOG+LIBRARY_GROUPS— every other ZIM, shown as one checklist per group (health,survival,practical,culture). Fields:id,group,label_key,title_key,stem(file name without the_YYYY-MM.zimdate; a{lang}placeholder means multilingual with English fallback, no placeholder means a single-language book that is tagged "[in English]" for other users),urls(mirror directories, primary first),size_mb(int, or{lang: mb}), optionalsymlink(stable name, default<id>.zim),desktop(launcher on the desktop instead of the library folder),only_langs(hide for other languages) andpresets(storage modes that preselect it; a book overBOOK_SPACE_SHARE(10%) of the free space is never preselected). To offer a new book, add one entry here plus its two i18n keys in both languages — nothing else changes. -
MAP_PRESETS— Organic Maps regions offered by the installer.countriesare top-level ids of the app'scountries.txt; every region below them is downloaded. Check new ids against the real file (it is in the Flatpak, underfiles/share/organicmaps/data/countries.txt). -
AI_MODEL_CONFIG— 5 LLM GGUF models, all fromhuggingface.co/unsloth:id model size symlink ia_minQwen3.5-0.8B-Q4_K_M ~508 MB minimal-model.gguf ia_baseQwen3.5-4B-Q4_K_M ~2.6 GB basic-model.gguf ia_medQwen3-8B-Q4_K_M ~4.8 GB intermediate-model.gguf ia_maxQwen3-14B-Q4_K_M ~8.6 GB advanced-model.gguf ia_ultragemma-4-26B-A4B-it-UD-Q4_K_M ~16.2 GB ultra-model.gguf Keep in sync with the
register_modelcalls inscripts/refugios-ai-selector.shwhen modifying AI models.
FAILED_ITEMS = []— global accumulator for non-fatal failures (shown in final summary)._write_log(msg)— strips ANSI codes (regex) and appends to/tmp/refugios-install.log.log_info(msg)/log_success(msg)— colored console + log file.log_err(msg, fatal=True)— red error;fatal=True→sys.exit(1);fatal=False→ append toFAILED_ITEMSand continue.SizeLogger— tracks disk space per phase (log_section,log_total).run_cmd(cmd, shell=True, check=True, quiet=False)— subprocess wrapper returning bool.download_with_aria2(url, dest_path, timeout=120, max_tries=3)— aria2c with 8 parallel connections, strict Linuxtimeoutwrapper, cleans.aria2control + partial files (success or failure).get_cmd_output(cmd)— captures stdout.certify_icon(fpath)/certify_all_desktop_icons(desktop_dir)— marks.desktopfiles as XFCE-trusted viagio set metadata::xfce-exe-checksum(SHA-256).OBSOLETE_EXEC_PATTERNS+cleanup_obsolete_icons(desktop_dir)— removes old vault script icons from previous refugiOS versions.ensure_install_icon(env, sys_info)— creates/usr/local/bin/refugios-install-wrapper.sh+ desktop re-install icon if missing.set_wallpaper(sys_info)— setsmedia/logo/fondo.pngfor XFCE (xfconf-query) and RPi (pcmanfm).SystemInfo— detects OS (Ubuntu/Debian/RPi via/etc/os-release+/proc/device-tree/model), RAM (/proc/meminfo), storage (shutil.disk_usage), GPU/VRAM (lspci), desktop env, language.fix_flatpak_permissions()— AppArmor unprivileged-userns patch for Ubuntu 24.04 / Debian 13.fix_rpi_pcmanfm_warnings()— disables PCManFM non-exec warning on RPi.sanitize_for_dialog(text)— CRITICAL: replaces Unicode typographic chars (•U+2022,–,—, smart quotes,…) with ASCII equivalents and encodes to latin-1 withreplace. Thedialoglibrary encodes strings as latin-1, so any non-ASCII user-facing string passed tod.msgbox/d.menu/etc. MUST be wrapped in this function or it will raiseUnicodeEncodeError.init_dialog(),multi_select_menu,single_select_menu,simple_question— TUI primitives wrappingdialog. Installed items are tagged with\Z1...installed_tag...\Zn(red) and pre-checked.TargetEnv— central path map under~/refugiOS/.sync_resources(env, sys_info, exec_path)— symlinks best ZIM/AI versions to stable names; creates/removes desktop launchers; cleans stale Knowledge icons.ensure_dirs(env)— creates the~/refugiOS/structure.install_package(env, name, is_rpi, appimage_url, appimage_name, flatpak_id, apt_deps)— the cascading installer engine (see §7).fetch_url(url)— simple HTTP GET with browser User-Agent.main()— orchestrates the full flow (see below).
- Root-guard (
os.geteuid() == 0→ exit). - Init dialog.
- Detect
SystemInfo. - Language selection (persistent via
i18n.save_lang). - System diagnosis dialog.
- Storage-mode presets: lite (<30 GB), standard (30–70 GB), rich (>70 GB) → default library preselections and AI models (Wikipedia is sized by free space instead).
- Rewrite-mode question (force re-download).
- Detect already-installed components (scan
versions/dirs). - Questionnaires: Wikipedia (single), one library checklist per group, maps (yes/no) + map regions (multi), extras (yes/no), AI models (multi), P2P preference (yes/no).
- Space estimation + critical-space warning + confirmation.
DEBUG=1→ dry-run exit (no changes, no downloads).- Execution phases:
- Phase 1: OS utilities & base deps (apt packages, language packs, AppArmor patch, RPi PCManFM patch).
- Phase 2: Kiwix Desktop (AppImage via scraped download.kiwix.org → Flatpak → APT).
- Phase 3: Knowledge bases / ZIMs (
install_zimfor the Wikipedia tier and each library book; see the download cascade below). - Phase 4: Organic Maps (Flatpak) + chosen map regions (
install_map_regions)refugios-maps.shlauncher.
- Phase 5: AI engine (Llamafile from GitHub releases) + selected GGUF models +
refugios-ai-selector.shlauncher. - Phase 6: Vault (
refugios-vault.py+i18n.pydeployed) + desktop icon. - Wrapper install icon, PCManFM quick-exec hack,
refugios-kiwix.shfetch,sync_resources,set_wallpaper, certify all icons,SizeLoggertotal.
- Final report: if
FAILED_ITEMS→ error summary dialog (dashes, not bullets); else → success dialog with total space used.
Prepares the minimum for the Python installer. set -e; creates ~/refugiOS/Scripts;
defines fallback t(); Developer Mode copies local scripts/i18n.sh, i18n.py,
install.py if present; otherwise downloads them from GitHub raw; sources i18n.sh;
checks/installs deps (python3 python3-dialog dialog aria2 pciutils wget curl bash jq rsync apt-utils flatpak); runs python3 install.py < /dev/tty (forces interactive
tty to fix EOFError from curl|bash pipes). DEBUG=1 skips apt operations.
Desktop launcher "Update refugiOS" runs refugios-update.sh, which downloads the
published install.sh and runs it with --update (with REFUGIOS_SRC_DIR set it uses
that checkout instead). install.sh forwards its arguments to install.py, whose
main() calls run_update() right after SystemInfo(), skipping the questionnaire.
collect_updates() returns dicts (label, size_mb, old_mb, apply) for: new
editions of installed catalog books (or the user-language book replacing an English
fallback), the Kiwix AppImage (checked against the published .md5), llamafile (checked
against the SHA-256 in the GitHub release asset digest), AI models whose published
SHA-256 differs from the saved .sha256, pending Flatpak updates of Organic Maps, Kiwix
and the translator, and map regions stored for an older Organic Maps data version.
Before collecting updates, refresh_scripts() replaces the launchers already deployed in
~/refugiOS/Scripts (DEPLOYED_SCRIPTS) with the published ones (the local checkout in
Developer Mode), via <file>.new + os.replace; it never adds a launcher the user did not
have. install.sh already refreshes i18n.sh/i18n.py on every run.
Invariant: the old version is removed only after the new one is verified
(update_book, update_kiwix_appimage, update_llamafile, update_model writes to
<file>.new and os.replaces it, update_map_regions removes old map folders only when
every region is in place). Items whose size does not fit in the free space plus
UPDATE_SPACE_MARGIN_MB are skipped. The normal installer also removes older editions of
a book once the newest one is verified (remove_older_zims).
Desktop launcher "Check refugiOS". Checks without any connection that books, AI
models and engine, Organic Maps regions, translator and vaults are complete and intact
(interrupted downloads, broken stable links, region sizes against the app's
countries.txt, LUKS magic of vault files, free space). --full also recomputes the
<file>.sha256 the installer saved and the maps' SHA-1. --quick|--full --no-dialog
prints the report to stdout (used by the tests); it is always saved to
~/refugiOS/check-report.txt. Exit code 1 when anything failed.
MODEL_MIN_USABLE_MB mirrors the thresholds of refugios-ai-selector.sh.
Interactive dialog TUI for create/open/close/delete encrypted LUKS containers.
- Imports:
os, sys, subprocess, shutil, re, json, math+i18n+dialog. Has a/dev/ttystdin fix for piped launches. - Vaults stored as
~/refugiOS/Vaults/<name>.img; mapper namevault_<name>; mount point~/Desktop/VAULT_<name>(or~/Escritorio/...). - Operations:
op_create(dd→cryptsetup luksFormat→mkfs.ext4),op_open,op_close(umount+cryptsetup close),op_delete. - USB import:
detect_usb_drivesvialsblk -J; suggests 1.5× used data;_import_usb_to_vaultrsyncs USB → vault. - Root-guard; uses
sudo cryptsetupfor all LUKS ops. os.system('clear')runs after eachyesnoconfirmation before launching commands, for clean terminal output.
Detects RAM (free -m) + VRAM (NVIDIA nvidia-smi, AMD /sys/class/drm/.../mem_info_vram_total,
Intel iGPU shares RAM); computes USABLE_MB = RAM + VRAM - 2048 (strict 2 GB OS safety
margin to avoid USB swap freeze); registers 5 models with min_usable_mb thresholds;
builds dialog menu showing only installed models with [OK]/[LOW_RAM] status and
auto-preselecting the most powerful fitting model; on launch sets -ngl 99 (full GPU
offload) if dedicated GPU, -ngl 0 if no AVX2 (avoids crashes on old/ARM CPUs); starts
llamafile --server on port 8080 with --reasoning off (only when the engine's --help
announces it: Qwen3.5 otherwise reasons until the 4096-token context is exhausted and never
answers; older engines reject the flag); opens epiphany-browser (or xdg-open) to the chat
UI. Runs clear after the dialog before launching llamafile.
Launches a ZIM file with Kiwix Desktop. Resolves symlinks via readlink -f (Flatpak
sandbox can't follow them); detects Kiwix binary in order: kiwix-desktop in PATH →
~/refugiOS/Apps/kiwix-desktop.appimage (with APPIMAGE_EXTRACT_AND_RUN=1) → Flatpak
org.kiwix.desktop (with --filesystem="${ZIM_DIR}:ro" for sandbox access) → any
kiwix AppImage found in Apps/.
Launches Organic Maps (Flatpak). Detects RPi 1/2/3/Zero via
/proc/device-tree/model; forces LIBGL_ALWAYS_SOFTWARE=1 on those; otherwise normal
flatpak run app.organicmaps.desktop.
install_package() in install.py:
- Raspberry Pi path: Overrides priorities → tries native APT first (many AppImages lack ARM builds); skips if no APT package.
- PC path (3 levels):
- AppImage via direct download with
aria2c→chmod +x. (Returns the path string on success.) - Flatpak — adds flathub remote if missing,
flatpak install flathub <id> -y. - APT —
sudo apt-get install -y <deps>.
- If all 3 fail →
log_err(..., fatal=False)appends toFAILED_ITEMSand continues. The installer never hard-stops on a single package failure.
- AppImage via direct download with
ZIM download cascade (download_zim, separate): the file is resolved in the
user's language, else English, from the first mirror listing that has it; then Kiwix
.meta4 metalink (aria2 spreads it over mirrors and checks piece hashes) → each mirror
directly, checked against the published .sha256 → BitTorrent (.torrent) → logged as
failed (fatal=False). With the P2P preference, BitTorrent goes first. The expected
hash is written next to the file as <file>.sha256.
Integrity rules (do not break them):
- A file with an
.aria2control file beside it is an interrupted download: never count it as installed nor link it (is_download_complete). - Match model files by exact name, never by prefix: a prefix also matches the
.aria2and.sha256files next to them. - GGUF models are checked against the SHA-256 Hugging Face returns in the
X-Linked-Etagheader of the (not followed) redirect (fetch_hf_sha256). - Map regions are checked against the size and
sha1_base64that the app's owncountries.txtlists, and downloaded for its data versionv.
Dual implementation mirroring each other. Supported languages: es (Spanish)
and en (English) only — hardcoded in validation lists. Roadmap mentions expanding.
- Global
REFUGIOS_LANG = "en"; config file~/.refugios_lang. load_lang()(called at import): reads config file → else autodetects from$LANGenv (splits on_, lowercases, checks es/en).save_lang(lang): writes config file + patches~/.bashrcwithexport LANG=<lang>_<ES|US>.UTF-8for session persistence.TRANSLATIONSdict: two sub-dicts'en'and'es', ~150 keys each.T(key): 3-level fallback —TRANSLATIONS[REFUGIOS_LANG].get(key)→TRANSLATIONS['en'].get(key)→keyitself.- Key naming: snake_case (e.g.
sys_diag_title,vault_create_title,install_finished_msg). Placeholders use positional{0},{1}via.format(). - Known gap:
setting_wallpaperis referenced ininstall.pybut not defined ini18n.py— handled viatry/exceptfallback to a Spanish literal.
refugios-maps.sh, refugios-ai-selector.sh
- Same
~/.refugios_langconfig +$LANGautodetect. - Variables named
t_<lang>_<key>;t()function echoes${!varname}with English fallback.export REFUGIOS_LANGpropagates to child processes.
Has its own inline es/en string blocks (welcome text, wrapper messages, auto-expand messages) resolved at image build time.
Add the key to BOTH i18n.py (en + es dicts) AND i18n.sh (if used by a bash
script), plus any build-script inline block if relevant. Keep keys grouped logically
with inline comments.
- Uses
python3-dialog(thedialoglibrary wrapping ncursesdialog). init_dialog()enables--colorsfor\Z1(red) tags marking installed items.- Three primitives:
multi_select_menu(d.checklist),single_select_menu(d.menu),simple_question(d.yesno). - CRITICAL latin-1 constraint:
dialogencodes strings as latin-1. Any non-ASCII user-facing string passed tod.msgbox/d.menu/d.checklist/d.yesnoMUST be wrapped insanitize_for_dialog()or it will raiseUnicodeEncodeError. Error summaries use-instead of•to avoid this. - Screen clear:
os.system('clear')(Python) /clear(Bash) is run after each dialog→command transition for clean terminal output. This is applied ininstall.py(after the "INSTALLATION STARTING" dialog and after each missing-script warning),scripts/refugios-vault.py(after eachyesnoconfirmation, before launchingdd/cryptsetup/mount/umount/rsync/os.remove), andscripts/refugios-ai-selector.sh(after the model menu, before launching llamafile).
- Console: ANSI-colored prefixes —
[*]blue (info),[X] ERROR:red,[v] SUCCESS:green,[!] WARNING:yellow. - File:
/tmp/refugios-install.log— ANSI codes stripped via regex; everylog_*writes there. - Build log:
scripts/build_refugios_<timestamp>.log(tee'd, gitignored). SizeLoggerrecords disk usage per phase with[Size Log] [Phase Name]markers.
log_err(msg, fatal=True)exits;log_err(msg, fatal=False)appends to globalFAILED_ITEMSand continues. The installer favors graceful degradation — a single component failure never hard-stops the whole install.- Critical-script pre-validation:
refugios-vault.py,refugios-kiwix.sh, andrefugios-ai-selector.share checked withos.path.isfile()afterfetch_script(). If missing: warn the user (log +d.msgboxwith a descriptive i18n message), skip their desktop icon, and continue the installation. Dedicated i18n keys:vault_script_missing,kiwix_script_missing,ai_script_missing. - Root-guard:
install.pyandrefugios-vault.pyrefuse to run as root (os.geteuid() == 0→ exit) and usesudoonly internally. - Downloads are wrapped with Linux
timeoutto prevent indefinite hangs;.aria2control + partial files are always cleaned (success or failure).
26 bilingual .md files (ES + EN mirrored pairs), GitHub Wiki format. Also
Home.md (wiki landing) and _Sidebar.md (wiki nav).
| Topic | ES file | EN file |
|---|---|---|
| Vision & user experience | Vision-y-Experiencia-ES.md |
Vision-and-User-Experience-EN.md |
| System architecture | Arquitectura-ES.md |
System-Architecture-EN.md |
| Comparison of solutions | Soluciones-Existentes-ES.md |
Comparison-of-Solutions-EN.md |
| Choosing install media | Eleccion-Medio-Instalacion-ES.md |
Choosing-Installation-Media-EN.md |
| Virtualization guide | Guia-Virtualizacion-y-Pendrive-ES.md |
Virtualization-Guide-EN.md |
| Xubuntu installation | Instalacion-Xubuntu-ES.md |
Xubuntu-Installation-EN.md |
| Raspberry Pi installation | Instalacion-Raspberry-ES.md |
Raspberry-Pi-Installation-EN.md |
| System image build | Construccion-Imagen-Sistema-ES.md |
System-Image-Build-EN.md |
| Compatibility table | Compatibilidad-ES.md |
Compatibility-EN.md |
| Security vaults | Bovedas-Criptograficas-ES.md |
Security-Vaults-EN.md |
| Unit cloning | Clonado-de-Pendrive-ES.md |
Cloning-Units-EN.md |
| Modules & roadmap | Modulos-y-Roadmap-ES.md |
Modules-and-Roadmap-EN.md |
When updating docs, update both the ES and EN pair. Roadmap items (Khan Academy,
Kolibri, Project Gutenberg, SDR, games, auto-updater, more i18n) live in
Modulos-y-Roadmap-ES.md / Modules-and-Roadmap-EN.md.
- Fork → branch
feature/<name>. - Commit messages in English, conventional-commits-like prefixes (
fix:,feat:,docs:,chore:). - Link PRs to Issues; discuss feature requests via Issues first.
- All code comments, variable names, and logic in English (per
CONTRIBUTING.md). - DO NOT add comments to code unless asked. Match existing style.
- Python: PEP-8-ish, 4-space indent, module docstrings, type-free. Section banners
with
# =====...comment blocks. Short function docstrings. - Bash:
set -ein critical scripts,trap cleanup EXITfor robust teardown, localized string variables.
There is no npm run lint / ruff / typecheck. After editing Python, verify syntax:
python3 -m py_compile install.py
python3 -m py_compile i18n.py
python3 -m py_compile scripts/refugios-vault.pyAfter editing Bash:
bash -n install.sh
bash -n scripts/refugios-ai-selector.sh
bash -n scripts/refugios-kiwix.sh
bash -n scripts/refugios-maps.sh
bash -n scripts/build_refugios.sh
bash -n scripts/test_boot.shbash tests/run_all.sh # whole suite (needs Docker; ~3-4 min)
bash tests/run_all.sh --quick # only what runs on the hostSee doc/Test-Suite-EN.md for running individual tests, building images without sudo,
and driving a full installation inside QEMU.
DEBUG=1 python3 install.py(orDEBUG=1 ... install.sh) — dry-run simulation: no system changes, no downloads, exits before execution phases.bash scripts/test_boot.sh— boot-test a built image in QEMU UEFI.
The project follows Keep a Changelog + Semantic Versioning. On a release:
- Add a new
## [X.Y] - YYYY-MM-DDentry toCHANGELOG.md(Spanish, with Corregido / Añadido / Cambiado / Eliminado subsections). - Bump the version badge in both
README.md(Versi%C3%B3n-X.Y) andREADME.en.md(Version-X.Y). - Update the "Historial de Versiones" / "Version History" section in both READMEs.
- Bump
- **Current version:**at the top of this file. - Commit on a branch, merge into
mainwith--no-ff, tagvX.Y, push both.
Triggered by a request such as "actualiza en GitHub las imágenes" / "update the
images". It rebuilds both base images from the current main, verifies them, publishes
them to the download server and updates every place that links to them. It takes roughly
two hours end to end, mostly unattended.
Credentials & Automated Uploads. .sftp in the repository root holds three lines:
user@hostpasswordremote_directory(e.g./var/www/refugiosor whatever the target path is on the remote server)
It is gitignored and must never be committed, printed, or pasted into a command line. Read it from inside automated scripts (such as scripts/publish_images.py). If it is missing, stop and ask the user for it — do not guess or look elsewhere.
-
Delete previous builds. Any
.imgleft from earlier work; they are several GB each and only cause confusion. -
Build both images with the current code, sequentially (parallel builds race for loop devices):
for L in es en; do docker run --rm --privileged -v "$PWD:/repo" -v ~/refugios-images:/out -v /dev:/dev \ -w /out refugios-test:trixie /repo/scripts/build_refugios.sh -s 16G -l $L \ > ~/refugios-images/build-$L.log 2>&1 done docker run --rm -v ~/refugios-images:/out refugios-test:trixie chown -R 1000:1000 /out
Check both logs end with a zero exit. About 30-40 minutes each. The
chownis needed or QEMU cannot read the images afterwards. -
Verify each image before publishing it. One command, and it must pass:
bash tests/verify_image.sh ~/refugios-images/refugios-base-16G-es.img --expandIt checks the artefact, not the build: that the filesystem is clean, that the thirteen artefacts the image must contain are inside it, and — with
--expand— that a copy dropped onto a 128 GB disk really grows its root partition. Without--expandit takes seconds; with it, about five minutes per image. Do not skip--expand: it is the only check that exercises what every real user hits.Read the boot screenshots too (
tests/qemu_boot_check.py, see the test suite guide): the desktop must come up with nofsckprompt.Why this exists: 0.23 shipped without the expansion service enabled and every signal said it was fine. The build exited 0, its log recorded the symlink as created, and the screenshot showed a correct desktop. None of those look inside the image, and a 16 GB image on a 16 GB disk cannot exercise the expansion at all — it is a no-op there.
-
Compress and decide the format. Use
7z(multithreaded; Info-ZIPzipis single threaded and takes far longer):7z a -tzip -mmt=10 -mx=5 refugios-base-16G-es.img.zip refugios-base-16G-es.img
Rule: if the
.zipis at most 60% of the.img, publish the compressed version; otherwise publish the raw.img. In practice it lands around 22%, so the published files are.img.zip.Then generate
SHA256SUMS.txtfor whatever gets published, with plain relative filenames and nothing else in it, so that a user who drops it next to the download can runsha256sum -con it unchanged:cd ~/refugios-images && sha256sum refugios-base-16G-es.img.zip refugios-base-16G-en.img.zip > SHA256SUMS.txt
It is published alongside the images and it is not optional: the download is several GB, and on a poor connection it arrives truncated with a USB that does not boot as the only symptom.
README.md,README.en.md,doc/Home.mdand the landing page all link tohttps://refugios.ganso.org/SHA256SUMS.txtand documentsha256sum --ignore-missing -c SHA256SUMS.txt; if the file is missing or stale, those instructions fail for everyone. The name never changes, so no link needs updating — but the contents do, on every republish.It must always list both images, even when only one was rebuilt. A sums file with a single line makes the documented check fail for the other language, which is the worst possible outcome: it tells a user with a perfectly good download that it is corrupt. If you no longer have the image you did not rebuild, take its hash from the copy already published, which is the one users get anyway:
curl -s https://refugios.ganso.org/refugios-base-16G-en.img.zip | sha256sum -
Upload by SFTP to the download server. Run the automated publishing script:
python3 scripts/publish_images.py
This script reads
.sftp, validates local checksums againstSHA256SUMS.txt, verifies the remote destination containsindex.html, uploads each image to a temporary name (.tmp), validates exact byte count on the server, rotates files atomically (<file>-><file>.old,<file>.tmp-><file>, remove<file>.old), uploadsSHA256SUMS.txtlast, and verifies the checksums remotely via SSH.Then verify end to end from the outside, which also proves the served bytes match the local ones:
curl -s https://refugios.ganso.org/SHA256SUMS.txt # both lines, right names curl -s https://refugios.ganso.org/refugios-base-16G-es.img.zip | sha256sum # equals its line
-
Update every link if the published filenames changed. They live in:
README.mdandREADME.en.md(download table, sizes, extraction instructions),doc/Home.md(both tables),doc/_Sidebar.md(both quick-start entries), and inline mentions indoc/Eleccion-Medio-Instalacion-ES.md,doc/Choosing-Installation-Media-EN.md,doc/Clonado-de-Pendrive-ES.md,doc/Cloning-Units-EN.md,doc/Instalacion-Xubuntu-ES.md,doc/Xubuntu-Installation-EN.md,doc/Construccion-Imagen-Sistema-ES.mdanddoc/System-Image-Build-EN.md. Verify none is left behind:grep -rn "refugios.ganso.org/refugios-base" --include="*.md" .
-
Record the date. Next to the download table in
README.md,README.en.mdanddoc/Home.mdthere is a line stating when the images were last updated and with which version. Update it; it is the only way a user can tell whether the download is current. -
Commit, tag and push, and add a
### Cambiadoentry toCHANGELOG.mddescribing what the new images contain. -
The landing page.
web/index.htmlis the landing page served at https://refugios.ganso.org, styled after ganso.org (Poppins + Bootstrap + Font Awesome).MANDATORY on every release/republish: Update the download button file sizes and advisory texts in
web/index.html(both in the Spanish and English blocks) to match the real compressed size of the new.img.zipfiles (e.g.2.9 GBand~2.9 GB), and uploadweb/index.htmlto the remote server alongside the images andSHA256SUMS.txt. The scriptscripts/publish_images.pyperforms this size synchronization and upload automatically. Always keep the logo credit in the footer intact. -
Stale files on the server. If the published names changed, the previous files stay behind and nothing links to them. Ask the user before deleting anything remote — the deletion is irreversible and is theirs to authorize. Verify the local checksums (
sha256sum -c SHA256SUMS.txt) before deleting the corresponding local copies. -
Redirect the retired URLs — do not just delete them. Old links keep circulating in forums, bookmarks and articles.
/refugios/.htaccesson the server holds this, and it must be extended whenever a published filename changes:Options -MultiViews Redirect 301 /refugios-base-16G-es.img /refugios-base-16G-es.img.zip Redirect 301 /refugios-base-16G-en.img /refugios-base-16G-en.img.zip
Options -MultiViewsis not cosmetic. Apache's content negotiation is enabled on that host, so after renaming…-es.imgto…-es.img.zipa request for the old name kept answering 200 with the ZIP bytes under the.imgname. Anyone following an old link downloaded a ZIP disguised as a disk image, flashed it, and got a USB that does not boot with no hint as to why. With MultiViews off the negotiation stops (it drops to300 Multiple Choices), and the explicitRedirect 301then sends the request to the real file, which the browser saves under its correct name.Verify all three behaviours after uploading the file — and check for a
500, which would mean the host does not allowOptionsin.htaccess; if that happens, remove the file immediately:curl -sI https://refugios.ganso.org/refugios-base-16G-es.img.zip | head -1 # 200 curl -sI https://refugios.ganso.org/refugios-base-16G-es.img | head -2 # 301 + Location curl -sI https://refugios.ganso.org/.htaccess | head -1 # 403
-
Verify the artefact, not the process. This is the lesson of 0.23, which shipped base images that never expanded the disk. Every signal said the build was fine — exit code 0, a log line reading
Created symlink …, a screenshot of a working desktop — and none of them looked inside the image, where the symlink was in fact missing. When you produce something that other people will download and flash, open it and check its contents (bash tests/verify_image.sh IMAGEN --expand). Related traps from the same incident:- A build log is not evidence. It records what a command reported, not what survived into the artefact.
- A boot screenshot proves very little. An image can boot perfectly to the desktop while missing something essential.
- The welcome popup reports the size of the disk, not of the partition. It says "114 GB" on a 128 GB stick whether or not the expansion worked. To check expansion, read the partition table.
- Testing a feature only where it is a no-op is not testing it. A 16 GB image on a 16 GB disk has nothing to expand; the case had to be built on purpose.
docker runwithout-isilently ignores a script fed on stdin and exits 0. A check written that way passes without checking anything — it happened while writingverify_image.shitself.
-
UnicodeEncodeErrorwithdialog(latin-1). Any non-ASCII char (bullets•, em-dashes, smart quotes, accented letters beyond latin-1) passed to adialogcall will crash. Always wrap user-facing text insanitize_for_dialog(). Use-instead of•in summaries. -
Forgetting
i18nkeys in both languages. Add new keys toenANDesdicts ini18n.py, and toi18n.shif a bash script uses them.T()falls back to English then to the key itself, so a missing key shows the raw key name to the user. -
Desync between
AI_MODEL_CONFIG(install.py),MODEL_MIN_USABLE_MB(refugios-check.py) andregister_modelcalls (refugios-ai-selector.sh). Keep them in sync when adding/removing/renaming models. -
Committing large binaries.
*.img,*.zim,*.gguf,*.appimageare gitignored — nevergit addthem. -
Running the installer as root.
install.pyandrefugios-vault.pyhard-refuse root; they usesudoonly internally for specific commands. -
curl|bashstdin issue.install.shrunspython3 install.py < /dev/ttyto fixEOFErrorwhen launched via a piped curl. Preserve this when modifyinginstall.sh. -
Flatpak sandbox can't follow symlinks.
refugios-kiwix.shresolves symlinks withreadlink -fand adds--filesystemfor Flatpak. Keep this when touching ZIM launching. -
XFCE
.desktoptrust..desktopfiles must be certified viagio set metadata::xfce-exe-checksum(certify_icon) or XFCE will show a "untrusted application" prompt.certify_all_desktop_iconsruns at the end of install;refugios-trust-launcher.shdoes it on first boot of a built image.
| File | Role | Lines |
|---|---|---|
install.py |
Main TUI installer wizard | ~1490 |
i18n.py |
Python localization (EN/ES) | ~384 |
install.sh |
Bootstrap launcher | ~107 |
scripts/refugios-vault.py |
LUKS vault manager TUI | ~564 |
scripts/refugios-ai-selector.sh |
AI model selector + llamafile launcher | ~191 |
scripts/refugios-kiwix.sh |
Kiwix/ZIM launcher | ~55 |
scripts/refugios-maps.sh |
Organic Maps launcher | ~19 |
scripts/build_refugios.sh |
Image builder (debootstrap) | ~577 |
scripts/test_boot.sh |
QEMU UEFI boot test | ~135 |
scripts/i18n.sh |
Bash localization | ~120 |
build_all.sh |
Build both ES+EN images | 2 |
tests/run_all.sh |
Entry point for the whole test suite | ~44 |
tests/unit_install.py |
Unit tests for install.py |
~290 |
tests/unit_bash.sh |
Tests for the Bash scripts | ~219 |
doc/Test-Suite-EN.md |
How the tests work and how to run them | ~250 |
- Understand the request — re-read the relevant file(s) with
Read/Grep/Globbefore editing. - Follow existing conventions — mimic code style, use existing libraries
(
i18n.T,run_cmd,log_*,sanitize_for_dialog), don't introduce new deps. - No comments unless asked.
- i18n every user-facing string — add keys to both
enandesini18n.py(andi18n.shif bash). - Wrap dialog text in
sanitize_for_dialog()if it could contain non-ASCII. - Verify syntax with
python3 -m py_compile/bash -nafter editing, and runbash tests/run_all.shbefore proposing the change. - Add a test for any behaviour you fix, and check it fails without your fix.
- Update
CHANGELOG.mdand both READMEs (version badge + history section) when releasing a new version. - Never commit unless explicitly asked. Stage only intended files; never commit secrets or gitignored binaries.