{
  description = "Genesis — evolutionary software development in Elixir. `nix run` for the CLI; `nix run .#desktop` for the native desktop app; `nix run .#desktop-smoke` for the manual packaged-app start-up smoke test; `nix develop` for the Tauri build environment.";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = nixpkgs.legacyPackages.${system};
        lib = pkgs.lib;

        # ── BEAM toolchain ──────────────────────────────────────────
        # Erlang/OTP 29 + Elixir 1.20, matching CI version pins.
        # The `packagesWith erlang_29` set defaults to Elixir 1.18, which cannot
        # compile the app: it refuses to escape a module attribute holding
        # compiled %Regex{} values into a function body (see
        # apps/evo_git/lib/evo_git/config/schema/llm_constraints.ex), so the
        # package set is extended to Elixir 1.20 instead of relying on that
        # default. This ONE binding feeds the release builds AND the dev shell,
        # so the two toolchains cannot drift apart.
        beamPkgs = (pkgs.beam.packagesWith pkgs.beam.interpreters.erlang_29).extend
          (final: prev: { elixir = final.elixir_1_20; });
        erlang = beamPkgs.erlang;
        elixir = beamPkgs.elixir;

        # ── Tauri v2 native dependencies (Linux only) ──────────────
        # These are the NixOS equivalents of the apt packages installed by
        # the GitHub Actions workflow (libwebkit2gtk-4.1-dev, librsvg2-dev,
        # libayatana-appindicator3-dev, libssl-dev, etc.).
        tauriNativeDeps = lib.optionals pkgs.stdenv.isLinux (with pkgs; [
          webkitgtk_4_1
          gtk3
          glib
          glib-networking # TLS support for WebKit HTTP requests
          librsvg
          libayatana-appindicator
          libsoup_3
          openssl
          xdo # libxdo — X11 automation (Tauri build-time dep)
        ]);

        # ── Tauri runtime helpers (Linux only) ─────────────────────
        tauriRuntimeDeps = lib.optionals pkgs.stdenv.isLinux [
          pkgs.dconf # GSettings backend (required by GTK at runtime)
          pkgs.hicolor-icon-theme # icon theme needed by app bundles
          pkgs.mesa # the flake's own EGL vendor (see __EGL_VENDOR_LIBRARY_DIRS)
        ];

        # ── Manual desktop start-up smoke test ──────────────────────
        # Boots the REAL packaged desktop app (Tauri shell in its `--headless`
        # mode → the bundled `genesis_desktop` Mix release → the dashboard on
        # HTTP) and asserts it serves the dashboard and shuts down cleanly.
        # This is the only test that exercises the packaged `vm.args` + ERTS, so
        # it is what catches boot-only regressions such as the shipped
        # `+t 80000` atom-table cap (which made the app fail to start on ALL
        # platforms with a silent, zero-log boot failure).
        # DELIBERATELY an app (never a flake `checks` entry, never wired into
        # CI): it builds the entire desktop app and boots a real BEAM, so it is
        # expensive and must only run when a release manager explicitly asks.
        # Exposed under `packages` too, so the app's program path resolves and
        # `nix eval .#desktop-smoke.drvPath` works — nothing builds it by
        # default.
        desktopSmoke = pkgs.writeShellApplication {
          name = "genesis-desktop-smoke";
          runtimeInputs = [
            self.packages.${system}.desktop
            pkgs.curl
            pkgs.coreutils
            pkgs.gnugrep
            pkgs.procps
          ];
          # GENESIS_DESKTOP_APP points the script at the packaged app; the
          # script body lives in nix/desktop-smoke.sh.
          text =
            ''export GENESIS_DESKTOP_APP="${self.packages.${system}.desktop}"'' + "\n"
            + builtins.readFile ./nix/desktop-smoke.sh;
        };
      in
      {
        # ── `nix build` / `nix run` ──────────────────────────────────
        # CLI app (both evo_git + evo_dash, no desktop flag).
        packages.default = pkgs.callPackage ./genesis.nix {
          src = self;
          beamPackages = beamPkgs;
        };

        # Tauri desktop app (genesis_desktop release + native WebView shell).
        packages.desktop = pkgs.callPackage ./genesis-desktop.nix {
          src = self;
          inherit (pkgs) rustPlatform makeWrapper pkg-config openssl file
            webkitgtk_4_1 gtk3 glib glib-networking librsvg
            libayatana-appindicator libsoup_3 xdo wrapGAppsHook3
            mesa libglvnd;
          beamPackages = beamPkgs;
        };

        # Manual start-up smoke test (derivation defined in the `let` block
        # above); exposed as a package so the app's program path resolves.
        packages.desktop-smoke = desktopSmoke;

        apps.default = {
          type = "app";
          program = "${self.packages.${system}.default}/bin/genesis";
        };

        apps.desktop = {
          type = "app";
          program = "${self.packages.${system}.desktop}/bin/genesis-desktop";
        };

        # `nix run .#desktop-smoke` — manual, release-time only.
        apps.desktop-smoke = {
          type = "app";
          program = "${self.packages.${system}.desktop-smoke}/bin/genesis-desktop-smoke";
        };

        # ── Development shell ────────────────────────────────────────
        devShells.default = pkgs.mkShell {
          # pkg-config must be in nativeBuildInputs so the Rust/Tauri build
          # can locate the webkit/gtk libraries via *.pc files.
          nativeBuildInputs = [ pkgs.pkg-config ];

          buildInputs = [
            # ── BEAM toolchain ──
            erlang
            elixir

            # ── Rust toolchain ──
            pkgs.cargo
            pkgs.rustc
            pkgs.rustfmt
            pkgs.clippy

            # ── Core build tools ──
            pkgs.gnumake
            pkgs.gcc # C compiler for NIF compilation (mdex, xqlite)
            pkgs.file # required by Tauri's bundling step
            pkgs.curl # for downloading vendor binaries

            # ── Vendor binaries (bundled into the release) ──
            pkgs.ripgrep
            pkgs.git
          ] ++ tauriNativeDeps
            ++ tauriRuntimeDeps;

          shellHook = ''
            ${lib.optionalString pkgs.stdenv.isLinux ''
              # Let GLib/GIO find the networking and dconf modules at runtime.
              export GIO_EXTRA_MODULES="${pkgs.glib-networking}/lib/gio/modules:${pkgs.dconf}/lib/gio/modules"
              # Work around WebKit rendering issues under certain compositors.
              export WEBKIT_DISABLE_DMABUF_RENDERER=1
              # The shell must resolve EGL from the flake's OWN mesa: libglvnd's
              # compiled-in vendor dir list starts with the host's
              # /run/opengl-driver/share/glvnd/egl_vendor.d, and a host mesa built
              # against a newer glibc than this shell's pin fails to dlopen
              # (GLIBC_2.4x not found) → WebKit aborts with
              # "Could not create default EGL display: EGL_BAD_PARAMETER".
              export __EGL_VENDOR_LIBRARY_DIRS="${pkgs.mesa}/share/glvnd/egl_vendor.d"
            ''}

            echo ""
            echo "  ┌─────────────────────────────────────────────┐"
            echo "  │  EvoX Genesis — NixOS Development Shell     │"
            echo "  └─────────────────────────────────────────────┘"
            echo ""
            echo "  Quick start:"
            echo "    nix run           — build & run Genesis CLI"
            echo "    nix run .#desktop — build & run EvoX Genesis (Tauri)"
            echo ""
            echo "  Toolchain:"
            echo "    Erlang/OTP : $(erl -noshell -eval '{ok,V}=file:read_file(filename:join([code:root_dir(),"releases",erlang:system_info(otp_release),"OTP_VERSION"])), io:format("OTP ~s",[string:trim(V)]), halt()' 2>/dev/null || echo 'unknown')"
            echo "    Elixir     : $(elixir --version 2>/dev/null | tail -1 || echo 'unknown')"
            echo "    Rust       : $(rustc --version 2>/dev/null || echo 'unknown')"
            echo ""
            echo "  ── Build the desktop app ─────────────────────"
            echo ""
            echo "  # 1. Fetch Elixir dependencies"
            echo "  mix deps.get"
            echo ""
            echo "  # 2. Build and digest frontend assets"
            echo "  mix assets.setup && mix assets.deploy"
            echo ""
            echo "  # 3. Install Tauri CLI v2 (first time only)"
            echo "  cargo install tauri-cli --version \"^2.0\""
            echo ""
            echo "  # 4. Bundle vendor binaries into the release"
            echo "  ./nix/bundle-vendor.sh"
            echo ""
            echo "  # 5. Build the Elixir release"
            echo "  MIX_ENV=prod mix release genesis_desktop"
            echo ""
            echo "  # 6. Place the release directory where Tauri expects it"
            echo "  rm -rf desktop/src-tauri/resources/genesis-backend"
            echo "  cp -a _build/prod/rel/genesis_desktop desktop/src-tauri/resources/genesis-backend"
            echo ""
            echo "  # 7. Build the Tauri desktop app"
            echo "  cd desktop/src-tauri && cargo tauri build"
            echo ""
          '';
        };
      }
    );
}