From 77ed54fe018c44498a9e4fbc15664f7bcb6b2808 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 23 Oct 2026 12:58:16 -0500 Subject: [PATCH] feat(nix-devshell): add nix development shell authoring skill - Add operational skill instructions and progressive validation protocol (<= 80 lines) - Add reference guides for design choices, native dependencies, authoring patterns, validation troubleshooting, and compatibility verification - Register nix-devshell in install.sh ACTIVE_PORTABLE_SKILLS - Document nix-devshell in Portable Core table in README.md --- README.md | 1 + install.sh | 2 +- skills/nix-devshell/SKILL.md | 75 ++++++++++ .../references/authoring-patterns.md | 103 +++++++++++++ .../nix-devshell/references/compatibility.md | 127 ++++++++++++++++ .../references/design-decisions.md | 137 ++++++++++++++++++ skills/nix-devshell/references/native-deps.md | 77 ++++++++++ .../references/validation-troubleshooting.md | 78 ++++++++++ 8 files changed, 599 insertions(+), 1 deletion(-) create mode 100644 skills/nix-devshell/SKILL.md create mode 100644 skills/nix-devshell/references/authoring-patterns.md create mode 100644 skills/nix-devshell/references/compatibility.md create mode 100644 skills/nix-devshell/references/design-decisions.md create mode 100644 skills/nix-devshell/references/native-deps.md create mode 100644 skills/nix-devshell/references/validation-troubleshooting.md diff --git a/README.md b/README.md index 397ed27..6bec537 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ Every skill features an explicit **"Your call"** checkpoint where the agent paus | **[`reconcile-docs`](skills/reconcile-docs/SKILL.md)** | `/reconcile-docs [path]` | Reconciles historical evidence, present code reality, and future plans into canonical repo docs (README, ARCHITECTURE, ADR, ROADMAP). | 37 lines | | **[`build-skill`](skills/build-skill/SKILL.md)** | `/build-skill [topic]` | Interactive design, sizing, authoring, and empirical dogfooding of agent skills. Enforces design review gate before file creation. | 49 lines | | **[`inspect-flake-update`](skills/inspect-flake-update/SKILL.md)** | `/inspect-flake-update` | Inspects updated flake.lock inputs, reviews upstream revisions, runs nix flake check, and drafts commit messages. | 46 lines | +| **[`nix-devshell`](skills/nix-devshell/SKILL.md)** | `/nix-devshell` | Authors, extends, validates, and troubleshoots project Nix development shells from repository evidence. | 75 lines | ### Vault Extensions (`extensions/`) diff --git a/install.sh b/install.sh index 2c468b8..409458d 100755 --- a/install.sh +++ b/install.sh @@ -33,7 +33,7 @@ while [[ $# -gt 0 ]]; do done # Active skills to install -ACTIVE_PORTABLE_SKILLS=(build-skill diagnose document git-commit inspect-flake-update journal-builder practice reconcile-docs) +ACTIVE_PORTABLE_SKILLS=(build-skill diagnose document git-commit inspect-flake-update journal-builder nix-devshell practice reconcile-docs) ACTIVE_EXTENSION_SKILLS=(draft-curation commit-logger) # Legacy / deprecated skills to clean up or back up if found in target diff --git a/skills/nix-devshell/SKILL.md b/skills/nix-devshell/SKILL.md new file mode 100644 index 0000000..779e3f8 --- /dev/null +++ b/skills/nix-devshell/SKILL.md @@ -0,0 +1,75 @@ +--- +name: nix-devshell +description: >- + Authors, extends, validates, and troubleshoots project Nix development shells (flake + devShells or classic shell.nix) from repository evidence. Use when creating or editing a + devShell, adding tools or native libraries to one, choosing between a flake and shell.nix, + or when nix develop or nix-shell fails to evaluate, build, start, or compile the project. +--- + +# Nix Dev Shell + +## Use when +- Creating, extending, or repairing a project's development shell, or diagnosing why it fails. +- Not for NixOS or Home Manager configuration, packaging the project itself, production + containers, or devenv/devbox/flox. Lock updates go to `inspect-flake-update`. + +## Steps +1. **Inspect before deciding.** Read the Nix files, `flake.lock` (pinned nixpkgs revision), + `.envrc`, language manifests, build scripts, CI, contributor docs, `git status`, and + `nix --version` with enabled features. Write a short inventory of what exists and which + conventions (workflow, helper library, systems, constructor, input policy) you will keep. +2. **Establish requirements** from that evidence: tools, runtimes, native libraries, compiler, + env vars, startup behavior, project commands, target systems. Ask only about gaps that + change the design and cannot be read from the repo. +3. **Choose the design** with [references/design-decisions.md](references/design-decisions.md): + keep the existing workflow, add only required systems and inputs, pick the smallest option + that meets the requirements. If anything is compiled or linked, also read + [references/native-deps.md](references/native-deps.md) before adding libraries or flags. +4. **Check version-sensitive mechanisms** (compiler overrides, env attributes, output selection, + hooks, platform metadata) against the pinned revision using + [references/compatibility.md](references/compatibility.md). If you cannot check, say so and + either take a route that does not depend on it or ask. +5. **Implement** in the project's existing style; syntax pitfalls and illustrative (unexecuted) + patterns are in [references/authoring-patterns.md](references/authoring-patterns.md). + Create and edit files only. Never run `git add`, `git commit`, `git stash`, or anything else + that changes the index or history. A new untracked file in a Git-backed flake is invisible + to flake evaluation: say so and record it as a required user action. +6. **Validate progressively** with the four levels in + [references/validation-troubleshooting.md](references/validation-troubleshooting.md): + evaluation, realization and shell start, environment check, project command. Run the + levels that apply, in order. A passing level is never evidence for a later one. +7. **Troubleshoot** by first naming the failing phase (evaluation, fetching, realization, shell + start, compilation, runtime) from the actual error, using the symptom table in the same + reference. Then follow `diagnose` for hypotheses and checks. Try the smallest justified fix; + do not rewrite working parts (for example a whole `shellHook`) to fix one line. +8. **Report** in the format below. + +## Report +- **Changes**: files created or edited, and the design choice with its evidence. +- **Validation**: one row per level: `passed` or `failed` with the exact command and the + observed output excerpt; `blocked` with the exact cause (for example "`flake.nix` untracked, + Git-filtered evaluation cannot see it"); or `not run` with the reason. Never list a command + you did not run in this session. Checks that do not depend on the blocked files still run, + but are not presented as proof that the shell works. +- **Unverified**: version-sensitive behavior not checked against the pinned revision, + platforms not tested, and anything inferred rather than observed. +- **User actions**: for example, track new files (by hand or with `git-commit`) and rerun + the blocked checks. + +## Your call +- Flake, classic shell.nix, or both, when the repo shows no preference and the choice changes + how people work. Otherwise recommend the smallest fit and state the trade-off. +- Adding systems, flake inputs, or helper libraries (flake-utils, flake-parts). +- Enabling unfree packages. +- Host-level fixes (nix-ld, NixOS configuration): recommend, never apply. +- Relying on a version-sensitive mechanism you could not verify for the pinned revision. + +## Done when +- The agreed files exist or are changed, the Git index and history are untouched, and the + report has a row for every validation level. + +## Hands off to +- `git-commit`: to track or commit the new and changed files. +- `diagnose`: when the root cause lies outside Nix (application bug, host fault). +- `inspect-flake-update`: to review a lock update. diff --git a/skills/nix-devshell/references/authoring-patterns.md b/skills/nix-devshell/references/authoring-patterns.md new file mode 100644 index 0000000..520e4eb --- /dev/null +++ b/skills/nix-devshell/references/authoring-patterns.md @@ -0,0 +1,103 @@ +# Authoring patterns + +Used at step 5. Write in the project's existing style first; these are fallbacks and pitfall +checks. Labels: [compatibility.md](compatibility.md#evidence-labels). + +> None of the snippets below has been evaluated, built, or entered. They are starting points. +> Confirm package names, systems, and APIs against the pinned nixpkgs before relying on them. + +## Nix syntax pitfalls (`Established`, Nix language manual and nix.dev "Nix language basics") + +- Every binding in `{ ... }` and `let ... in` ends with `;`. `{ a.b = 1; }` means + `{ a = { b = 1; }; }`. +- Lists are whitespace-separated, no commas. Function application binds tighter than list + construction, so `[ pkgs.python3.withPackages (ps: [ ps.requests ]) ]` is a two-element list + (a function and a lambda) and fails during evaluation (commonly "cannot coerce a function to + a string"). Parenthesize calls inside lists: + ```nix + packages = [ (pkgs.python3.withPackages (ps: [ ps.requests ps.pytest ])) ]; + ``` +- `inherit (pkgs) git curl;` copies named attributes. `with pkgs; [ git curl ]` brings `pkgs` + into scope, but explicit `let` and function bindings shadow `with`: if `system` is bound by + `let`, `with pkgs; [ system ]` gives the `let` value, not `pkgs.system`. Avoid nested + `with a; with b;`; prefer `pkgs.` or `inherit` for short lists. +- Indented strings `'' ... ''` (used for `shellHook`): `${expr}` is Nix interpolation at + evaluation time. Write `''${BASH_VAR}` to emit a literal `${BASH_VAR}` for Bash; plain + `$VAR` without braces passes through. Write `'''` for a literal `''`. + +## mkShell argument reference (`Contextual`; check the pinned API) + +```nix +pkgs.mkShell { + packages = [ pkgs.rustc pkgs.cargo pkgs.rust-analyzer ]; # tools + nativeBuildInputs = [ pkgs.cmake pkgs.ninja ]; # build-platform tools, hooks + buildInputs = [ pkgs.openssl pkgs.zlib ]; # libraries linked against + inputsFrom = [ ]; # reuse a package's inputs + RUST_BACKTRACE = "1"; # flat env attribute + shellHook = ''export REPO_ROOT="$PWD"''; # runtime setup only +} +``` + +Include only the arguments the requirements need. The roles are explained in +[design-decisions.md](design-decisions.md#6-where-each-dependency-goes). + +## Pattern 1: minimal flake, one intended system + +```nix +{ + description = "Project development shell"; + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + outputs = { nixpkgs, ... }: + let + pkgs = nixpkgs.legacyPackages.x86_64-linux; + in { + devShells.x86_64-linux.default = pkgs.mkShell { + packages = [ pkgs.git ]; + }; + }; +} +``` + +Replace the system with the project's actual one(s); add systems only when required and the +dependencies support them. The nixpkgs branch is a project decision (see +[design-decisions.md](design-decisions.md#3-nixpkgs-inputs-and-lock-policy)). + +For several systems without an extra input (`Contextual`, one option among several): + +```nix +let + systems = [ "x86_64-linux" "aarch64-darwin" ]; # only the systems the project needs + forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); +in { + devShells = forAllSystems (pkgs: { default = pkgs.mkShellNoCC { packages = [ pkgs.jq ]; }; }); +} +``` + +## Pattern 2: classic shell using the caller's package set + +```nix +# shell.nix +{ pkgs ? import { } }: +pkgs.mkShellNoCC { + packages = [ pkgs.nodejs pkgs.pnpm pkgs.typescript-language-server ]; +} +``` + +This follows the caller's `NIX_PATH` and is not a shared pin. For collaboration use the +project's existing pinning mechanism or a verified revision and hash. Never write a placeholder +hash and present it as runnable. + +## Pattern 3: direnv + +`.envrc` with `use flake` (flake) or `use nix` (shell.nix), per Ayats 2023 and Austin's +tutorial. Requires direnv (and usually nix-direnv) and the user's own `direnv allow`; do not run +`direnv allow` on the user's behalf. + +## Platform-conditional packages + +```nix +packages = [ pkgs.jq ] ++ pkgs.lib.optionals pkgs.stdenv.isLinux [ pkgs.inotify-tools ]; +``` + +Check the package's `meta.platforms` in the pinned nixpkgs first +([compatibility.md](compatibility.md#checking-the-pinned-revision)). diff --git a/skills/nix-devshell/references/compatibility.md b/skills/nix-devshell/references/compatibility.md new file mode 100644 index 0000000..d7f472b --- /dev/null +++ b/skills/nix-devshell/references/compatibility.md @@ -0,0 +1,127 @@ +# Compatibility, verification, and source boundaries + +Used at step 4 (checking version-sensitive behavior) and step 8 (reporting unverified items). + +## Evidence labels + +Every claim in this skill's references carries one of five labels: + +- `Established`: directly supported by official Nix / Nixpkgs reference manuals or inspected + source code for the stated version. +- `Recommended`: supported by practical reports in the corpus (such as `mkShell` over naked + derivations, or modest `shellHook`s), not a hard language rule. +- `Contextual`: depends on project workflow, team, or tooling; sources in the corpus legitimately + disagree (for example flake vs `shell.nix`, `flake-utils` vs `lib.genAttrs`). +- `Synthesis`: operational agent policy derived to prevent common mistakes (inspect first, + preserve conventions, never stage files silently, separate validation levels). +- `Unresolved`: behavior that varies across Nix or nixpkgs versions, platforms, or external tools + and was not verified across all target revisions. Must be checked against the target project's + pinned revision before relying on it. + +## Compatibility baseline policy + +Do not assume a numeric minimum Nix version or a universal supported nixpkgs release range: + +1. **Use the target project's lock and baseline.** Read `flake.lock` (or classic pin in + `shell.nix` / `npins` / `niv`) for the exact nixpkgs commit, and check `nix --version` plus + enabled features on the host or CI config. +2. **Verify version-sensitive APIs against that pin.** If a project has no lock or declared + baseline, state the evidence version you are drawing from and make the pin an explicit + project decision. +3. **Never promise broader compatibility than you have verified.** + +## Checking the pinned revision + +When a task touches a version-sensitive mechanism, check the project's locked nixpkgs before +relying on it: + +1. **Find the pinned commit** from `flake.lock` (`nodes.nixpkgs.locked.rev`) or `nix flake metadata`. +2. **Inspect via local evaluation against the locked input** when Nix is available: + - Check package existence or outputs: + `nix eval .#devShells..default` or + `nix eval --inputs-from . nixpkgs#.outputs` + - Check platform support: + `nix eval --inputs-from . nixpkgs#.meta.platforms` + - Locate or read nixpkgs source files in the local store if already fetched: + `nix eval --inputs-from . --raw nixpkgs#outPath` (then read `pkgs/build-support/mkshell/default.nix` + under that store path if present locally). +3. **If the locked source is not available locally and cannot be fetched**: + - State clearly in the report what could not be verified against the pinned revision. + - Prefer a conservative pattern that does not depend on the unverified detail, or ask the user + before relying on it. + +## Version-sensitive items (`Unresolved` unless checked on the target pin) + +- **Experimental feature flags**: Nix 2.35 documentation still marks `nix-command` and `flakes` + experimental upstream, though some distributions enable them by default. Check the host. +- **Output attribute names**: current manuals use `devShells..default` and warn on legacy + `devShell.`. Check the project's existing outputs and target Nix version. +- **`mkShell` internals**: current mutable nixpkgs `master` (`pkgs/build-support/mkshell/default.nix`) + maps `packages` into `nativeBuildInputs`, merges selected `inputsFrom` attributes, drops the + `inputsFrom` derivations themselves from the merged list, and concatenates their shell hooks. + An immutable reference example is nixpkgs 23.11 commit `057f9aecfb71c4437d2b27d3323df7f93c010b7e` + (used by the workspace's `cowsay` template), linked at: + - `https://github.com/NixOS/nixpkgs/blob/057f9aecfb71c4437d2b27d3323df7f93c010b7e/pkgs/build-support/mkshell/default.nix` + - `https://github.com/NixOS/nixpkgs/blob/057f9aecfb71c4437d2b27d3323df7f93c010b7e/pkgs/top-level/all-packages.nix` + Note: that 23.11 pin is an example snapshot only, and its exact file text was not retrieved + during static audit; verify against the target project's own lock if exact merge or hook + ordering matters. +- **Multi-output `.dev` resolution and setup hooks**: which output a bare package reference + selects, and which hooks populate `PKG_CONFIG_PATH`, `CMAKE_PREFIX_PATH`, or compiler wrapper + variables, depend on the individual package and nixpkgs revision. +- **Environment variable attributes**: flat attributes (`FOO = "bar";`) are documented in the + nix.dev tutorial pinned to nixpkgs 24.05. Nested `env = { ... };` is a `mkDerivation` + structured-attribute interface and is not established as portable `mkShell` guidance across + revisions. +- **Compiler / `stdenv` overrides**: `mkShell.override { stdenv = ...; }` is the nixpkgs pattern + used by `mkShellNoCC` (and shown in a 22.05-era Discourse thread for `clangStdenv`), but the + available stdenv variants and override behavior must be checked on the target revision and OS. +- **Platform and Darwin SDKs**: package availability and macOS SDK / framework handling change + across nixpkgs releases. Never claim a shell works on Darwin or Linux unless verified on that + platform or restricted to evaluated metadata. +- **`buildFHSEnv`**: Linux-only and depends on host user-namespace support. + +## Update tooling and tarball inputs + +- **Nix locking vs dependency bots**: Nix can lock both `github:NixOS/nixpkgs/...` and + `https://channels.nixos.org/...` tarball URLs in `flake.lock`. Whether an automated bot can + update that URL is a separate tool question. +- **Renovate scope**: Renovate's Nix manager documentation (reviewed at version 44.181.0; beta / + opt-in) documents `flake.nix` with the `git-refs` datasource and delegates lock file + maintenance to Nix. Exact handling of `channels.nixos.org` tarball URLs and compression formats + depends on the Renovate version and endpoint configuration (discussed in the Sep 2026 Discourse + thread "PSA: Use nixos.org tarballs for your flake inputs!"). +- **Binary cache availability**: neither a GitHub URL nor a channel tarball URL guarantees that + every derivation in a shell is prebuilt by Hydra. + +## Source attribution + +- **Manuals & external docs**: + - Nix 2.34.9 / 2.35 Reference Manual: + [nix develop](https://nix.dev/manual/nix/2.35/command-ref/new-cli/nix3-develop.html), + [nix flake check](https://nix.dev/manual/nix/2.35/command-ref/new-cli/nix3-flake-check.html), + [nix flake](https://nix.dev/manual/nix/2.35/command-ref/new-cli/nix3-flake.html), + [Experimental features](https://nix.dev/manual/nix/2.35/development/experimental-features) + - nix.dev: + [Flakes concepts](https://nix.dev/concepts/flakes), + [Declarative shell environments](https://nix.dev/tutorials/first-steps/declarative-shell), + [FAQ: non-Nix executables](https://nix.dev/guides/faq.html#how-to-run-non-nix-executables), + "Nix language basics" tutorial + - Nixpkgs Manual: + [Setup hooks](https://nixos.org/manual/nixpkgs/stable/#sec-setup-hooks), + [FHS environments](https://nixos.org/manual/nixpkgs/stable/#sec-fhs-environments) + - Mutable nixpkgs master references (not cross-version proof): + [mkshell/default.nix](https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/mkshell/default.nix), + [stdenv/generic/setup.sh](https://github.com/NixOS/nixpkgs/blob/master/pkgs/stdenv/generic/setup.sh) + - Renovate: [Nix manager docs](https://docs.renovatebot.com/modules/manager/nix/) +- **Corpus articles & book material** (used for context and practical reports, not normative specs): + - Julien Ayats, "The Nix development workflow" (May 28, 2023) + - Austin, "How I've Been Using Nix Flakes (And What You Can Do With Them)", DEV Community (Feb 19, references nixos-24.11) + - NixOS Discourse, "Looking for clarity on Nix developer shells and their design" (Oct 27-29, 2025) + - NixOS Discourse, "PSA: Use nixos.org tarballs for your flake inputs!" (Sep 2025 - Sep 2026) + - NixOS Discourse, "Nix Flakes best practices question" (Mar-Apr 2021) + - NixOS Discourse, "Tips&Tricks for NixOS Desktop" (May 2023) + - NixOS Discourse, "How to make mkShell to use clang's stdenv" (2020 / nixpkgs 22.05 era) + - AdrienLemaire, GitHub issue #19 "Best practices for dev shells" (Jan 8, 2025) + - Luc Perkins, "Best practices for Nix at work" (Mar 24, 2025, includes "Split things up") and "Building a highly optimized home environment with Nix" (Sep 15, 2022, includes Nome) + - Gabriella Gonzalez, *NixOS in Production* (chapters on Setup, Flakes, BigPicture, CI/CD, IntegrationTesting, and the `cowsay` template) diff --git a/skills/nix-devshell/references/design-decisions.md b/skills/nix-devshell/references/design-decisions.md new file mode 100644 index 0000000..980e2c5 --- /dev/null +++ b/skills/nix-devshell/references/design-decisions.md @@ -0,0 +1,137 @@ +# Design decisions + +Used at step 3. Pick each option from repository evidence; none of these is a universal default. +Evidence labels (`Established`, `Recommended`, `Contextual`, `Synthesis`, `Unresolved`) are +defined in [compatibility.md](compatibility.md#evidence-labels). + +## 0. What a dev shell is + +- `Established` (Nix 2.35 `nix develop` manual): `nix develop` starts Bash with an environment + nearly identical to a derivation's build environment. Classic `nix-shell` is related but not + identical in every detail. +- `Established`: neither command is a container or sandbox. Commands run as the user, with the + user's filesystem, network, home directory, and host configuration. +- `Established`: `mkShell`, `stdenv`, `packages`, `buildInputs`, `nativeBuildInputs`, + `shellHook`, and `lib.genAttrs` are nixpkgs conventions, not Nix language constructs. Language + questions go to the Nix manual; constructor behavior goes to the pinned nixpkgs. +- `Recommended` (2025 Discourse thread "Looking for clarity on Nix developer shells"): use + `mkShell` / `mkShellNoCC` for nixpkgs-based shells. That thread reports practical problems + when a bare derivation bypasses setup hooks. A raw derivation is a deliberate alternative that + must provide what its consumer expects, not something that is impossible. + +## 1. Flake, classic shell.nix, or both + +Inputs: existing files, Git state, contributors, CI, Nix version and enabled features, pinning +and update policy, explicit user request. An existing workflow wins unless a requirement says +otherwise. + +| Workflow | Fits when | Trade-offs | +|---|---|---| +| Flake `devShells` | Flake already present; a committed input lock is wanted; contributors and CI can use the flake CLI | Lock pins the input graph. Flake features are still marked experimental upstream (Nix 2.35); distributions may enable them. Git-backed source omits untracked paths. | +| Classic `shell.nix` | Existing nix-shell workflow; flakes unavailable or disallowed; user asks for it | No flake.lock. Uses ambient `` unless an explicit pinning mechanism is added. | +| Both | Contributors need both commands and the extra maintenance is acceptable | Keep one canonical definition and have the other reuse it, to avoid drift. | + +`Contextual`: the sources disagree by audience. Austin's DEV tutorial ("How I've Been Using Nix +Flakes", Feb 19, references nixos-24.11) values flake.lock. Ayats ("The Nix development +workflow", May 28 2023) recommends shell.nix when simplicity matters and you are unsure, and +shows both. Neither is the rule. Ask the user only if the choice changes how people work and +evidence gives no safe default; otherwise recommend the smallest fit and state this trade-off. + +## 2. Which command does what + +- `nix develop`: enter a derivation's build environment, usually the flake's devShell. +- `nix-shell`: classic shell workflow; reads `shell.nix` (or `default.nix`). +- `nix shell`: temporarily adds packages to PATH. Right for one-off tools; it does not define a + project shell. +- `nix run`: runs an app or package's program; not an interactive dev shell. + +`Synthesis`: a tool the project needs every day (build, lint, test, formatter named in CI or +docs) belongs in the devShell. A tool needed once by one person (poke an endpoint, inspect a +file) is a `nix shell nixpkgs#` call, not a devShell edit. Exact options differ by Nix +version; check the local command reference. + +## 3. nixpkgs inputs and lock policy + +- `Established` (Nix 2.35 flake reference): `flake.nix` may name an unlocked reference; + `flake.lock` records the resolved input graph. +- `Established`: a lock pins inputs. It does not pin Nix itself, host state, runtime behavior, + package availability, or later downloads by npm, pip, cargo, and similar tools. +- `Contextual`: an indirect registry reference is a convenience choice, not automatically an + error. For shared projects make the source and update policy visible, and follow the project's + existing lock convention. +- `Contextual`: GitHub and channels.nixos.org tarball inputs differ in availability, caching, + API limits, and dependency-bot support (Sep 2026 Discourse thread "PSA: Use nixos.org tarballs + for your flake inputs!", version-specific and evolving). Locking an input, a bot updating it, + and the binary cache having its builds are three separate questions. See + [compatibility.md](compatibility.md#update-tooling-and-tarball-inputs). +- `Contextual`: `inputs..inputs.nixpkgs.follows = "nixpkgs"` shares one nixpkgs node when + that is compatible and intended. It is optional; a dependency may deliberately need its own + pin. Multiple nixpkgs nodes are not automatically wrong. +- Never add an input that the requirements do not need. + +## 4. Supported systems + +- Derive systems from contributors, CI, and package availability. A single-system output is + correct for a single-system project. Do not add four systems by default. +- `Contextual`, no consensus: inline `nixpkgs.lib.genAttrs` avoids an extra input for small + flakes (Luc Perkins, "Best practices for Nix at work", Mar 24 2025, "Split things up" + subsection argues for fewer inputs). flake-utils is used by Austin's tutorial and several + "NixOS in Production" templates. flake-parts fits an existing modular project. In an existing + project, keep whatever it already uses. +- For a package that exists only on some platforms, check its `meta.platforms` in the pinned + nixpkgs and include it conditionally (for example `lib.optionals pkgs.stdenv.isLinux [ ... ]`) + instead of adding or dropping systems. Darwin SDK behavior is nixpkgs-version-sensitive. + +## 5. Shell constructor + +| Constructor | Use when | Caveats | +|---|---|---| +| `pkgs.mkShell` | A C/C++ compiler or native build support is needed | Compiler, wrapper, hardening, and SDK details vary by platform and revision. Adding another compiler package does not necessarily make it `CC`. | +| `pkgs.mkShellNoCC` | No standard compiler toolchain is needed | A package manager may later compile native extensions and need a compiler. A smaller closure is not guaranteed. | +| Custom stdenv / `mkShell.override` | The project needs a specific compiler or toolchain | Version-sensitive. See [native-deps.md](native-deps.md#selecting-a-compiler). | +| `pkgs.buildFHSEnv` | Linux software that expects FHS paths | Linux only. See [native-deps.md](native-deps.md#foreign-binaries-on-nixos). | + +## 6. Where each dependency goes + +- `Established` for current nixpkgs master, `Unresolved` for other revisions: `mkShell` maps + `packages` into `nativeBuildInputs`, and merges the input lists of `inputsFrom` derivations + (dropping those derivations themselves) and their shell hooks. Check the pinned source before + relying on exact merge or hook order ([compatibility.md](compatibility.md#checking-the-pinned-revision)). +- `packages`: concise list for ordinary shell tools where native-input semantics fit. +- `nativeBuildInputs`: tools that run on the build platform and their setup hooks. + `buildInputs`: libraries for the host/target. They are not interchangeable by definition, + especially when cross-compiling. +- `inputsFrom = [ self.packages.${system}.default ]`: reuse an existing package's build inputs, + then add only the missing developer tools. The "NixOS in Production" `cowsay` template shows + this. Inspect what is inherited before adding duplicates. Use it only when such a package + exists; it is not a default. +- Native libraries, outputs, `pkg-config`, hardening: [native-deps.md](native-deps.md). + +## 7. Environment variables and shellHook + +- `Established` for nixpkgs 24.05 (nix.dev "Declarative shell environments" tutorial, which + pins 24.05), `Unresolved` for other revisions: flat, non-reserved, string-coercible mkShell + attributes such as `GREETING = "hello";` become shell variables. Names must not collide with + derivation attributes. Variables the shell protects from attribute overrides need `shellHook` + (the tutorial's "environment variables" and "startup commands" sections). +- `Unresolved`: a nested `env = { ... }` attribute is a `mkDerivation` structured-attributes + interface, not an established mkShell API. Do not use it unless the pinned source supports it. +- `Recommended` (Ayats 2023): `shellHook` is for runtime-dependent setup only. Keep it short, + idempotent (safe to run twice), and quiet. +- `Synthesis`: a hook that `exec`s another shell can break `nix develop --command`, `nix-shell + --run`, and environment capture (direnv). The idea comes from a user proposal in GitHub + discussion #19 (AdrienLemaire, Jan 8 2025), not a recommendation. Avoid it unless required + and tested for the actual invocation. To use your own interactive shell, prefer direnv. +- direnv / nix-direnv activate the environment in the user's existing shell (`use flake` or + `use nix` in `.envrc`). They need direnv installed and `direnv allow` by the user. + +## 8. Language toolchains + +- Read `rust-toolchain.toml`, `Cargo.toml`, `go.mod`, `package.json`, `.nvmrc`, + `pyproject.toml`, `.python-version`, and build scripts for required versions. +- Prefer the matching nixpkgs package when its version fits (check in the pinned revision). Use + an overlay or another pinning method only when an exact version or target requires it, and + treat that as an input-adding decision for the user. +- `Contextual`: a hybrid setup, where Nix supplies runtimes, compilers, and native libraries and + the ecosystem lockfile manages application dependencies, is often practical. It does not make + those later downloads Nix-reproducible. Follow the project's package-manager conventions. diff --git a/skills/nix-devshell/references/native-deps.md b/skills/nix-devshell/references/native-deps.md new file mode 100644 index 0000000..7a011bc --- /dev/null +++ b/skills/nix-devshell/references/native-deps.md @@ -0,0 +1,77 @@ +# Native dependencies, compilers, and linking + +Used at step 3 when anything is compiled or linked, and at step 7 for header, library, compiler, +or foreign-binary failures. Labels: [compatibility.md](compatibility.md#evidence-labels). + +## Keep the mechanisms apart + +Four different things can make a library usable. Diagnose which one the build actually relies +on before adding anything: + +1. **Output selection**: nixpkgs packages can have several outputs (`out`, `lib`, `dev`, ...); + contents vary per package. `Unresolved`: which output a bare package reference contributes + (for example whether headers from `dev` arrive) is package- and revision-dependent. When a + consumer needs an include or library path, inspect the actual outputs in the **pinned** + nixpkgs (commands in [compatibility.md](compatibility.md#checking-the-pinned-revision)) and + select one explicitly (`pkgs.zlib.dev`) if needed. +2. **Setup hooks**: shell code provided by individual packages. `Established` (nixpkgs manual, + setup-hook overview; current setup.sh): hooks run for inputs and may add compiler flags, + pkg-config paths, CMake metadata, or other variables, but only when that package ships an + applicable hook. There is no universal list of variables a library will set. +3. **Compiler wrapper flags**: the nixpkgs compiler wrapper adds include and linker flags for + inputs. `Unresolved`: which variables carry them, and their exact behavior, vary by platform + and revision; read them from the shell (`nix develop --command env`) rather than assuming. +4. **Build-system discovery**: `pkg-config` (reads `.pc` files), CMake `find_package`, Meson, + or hard-coded flags such as `-lz`. + +Rule: add `pkg-config` only when the build queries `.pc` metadata (a `pkg-config` call in a +Makefile, `PKG_CHECK_MODULES`, Meson `dependency()`, a crate's `pkg-config` build dependency). +A Makefile that only passes `-lfoo` usually needs the library and a working compiler, not +pkg-config. `Recommended` basis: Ayats 2023 explains outputs and pkg-config use for C/C++. + +## Placing native inputs + +- Compiler needed: use `mkShell`, not `mkShellNoCC`. +- Libraries the program links against: `buildInputs`. Tools that run during the build + (`pkg-config`, `cmake`, `ninja`, code generators): `nativeBuildInputs` or `packages`. + The roles matter most when cross-compiling ([design-decisions.md](design-decisions.md#6-where-each-dependency-goes)). +- Language extensions compiled by a package manager (Python wheels, Node native modules, Rust + `-sys` crates) need the compiler and the C library in the shell too, even when the project + "is not C". + +## Selecting a compiler + +- `Established` pattern, revision-sensitive: nixpkgs defines `mkShellNoCC` as + `mkShell.override { stdenv = stdenvNoCC; }`. The same shape selects a compiler, for example + `(pkgs.mkShell.override { stdenv = pkgs.clangStdenv; }) { ... }`. Evidence: the nixpkgs + definition and a nixpkgs-22.05-era Discourse thread ("How to make mkShell to use clang's + stdenv"); neither is a contract for every later revision. +- `Unresolved`: putting `clang` in `packages` does not guarantee it becomes `CC`; the earlier + claim that it always collides was not established. +- Before using an override: confirm in the pinned nixpkgs that `mkShell` accepts `override` + with `stdenv` and that the chosen stdenv attribute exists for each target system + ([compatibility.md](compatibility.md#checking-the-pinned-revision)). If you cannot confirm, + mark it unverified in the report and get the user's decision. + +## Hardening flags + +If a build fails on a hardening-related flag, read the actual compiler invocation and error. +Disable only the specific flag that the evidence implicates (for example via `hardeningDisable` +after checking the pinned API), never all hardening by default. + +## Foreign binaries on NixOS + +`Established` (nix.dev FAQ, "How to run non-Nix executables"; nixpkgs manual on FHS +environments): generic dynamically linked Linux binaries often fail on NixOS because there is no +global library path or FHS layout. A dev shell does not change that. Diagnose first +(`file `, the reported interpreter, `ldd` output, the exact error): + +| Evidence | Likely cause | Options, in order | +|---|---|---| +| "No such file or directory" for a binary that exists | Missing ELF interpreter (for example `/lib64/ld-linux-x86-64.so.2`) | Use the nixpkgs package; patch interpreter and rpath (`autoPatchelfHook`); compatibility layer | +| Interpreter present, `cannot open shared object file` | Missing shared libraries | Nixpkgs package; supply or patch the libraries; host-configured `nix-ld` | +| Program expects `/usr/...` paths, launches bundled or self-updating executables | FHS path assumptions | `buildFHSEnv` (Linux only; check user-namespace support on the host) | +| Wrong architecture, missing runtime data, GPU/driver issues, application bugs | Different problem | Neither FHS nor nix-ld fixes these by itself | + +`nix-ld` is NixOS host configuration: recommend it, do not apply it. None of these is a macOS +remedy. Language-downloaded artifacts (prebuilt wheels, npm binaries) fall in the same table. diff --git a/skills/nix-devshell/references/validation-troubleshooting.md b/skills/nix-devshell/references/validation-troubleshooting.md new file mode 100644 index 0000000..4d06aa9 --- /dev/null +++ b/skills/nix-devshell/references/validation-troubleshooting.md @@ -0,0 +1,78 @@ +# Validation and troubleshooting + +Used at step 6 (validation), step 7 (troubleshooting), and step 8 (reporting). +Labels: [compatibility.md](compatibility.md#evidence-labels). + +## 1. Execution phases (`Established`) + +Every failure happens in a specific phase. Name the phase from the error output before proposing +a fix: + +| Phase | Typical work | Boundary and common failures | +|---|---|---| +| Evaluation | Parse and evaluate Nix expressions; produce `.drv` descriptions | Syntax errors, missing attributes, type errors ("cannot coerce a function to a string"), unfree rejection, missing local files omitted from a Git-backed flake source. Flake purity restricts mutable evaluator state; classic expressions may read `` from `NIX_PATH`. | +| Source / dependency acquisition | Fetch flake inputs, tarballs, and source trees | even a locked input may still need to be fetched if not in the local store. Network, authentication, or substituter errors happen here, not in pure evaluation. | +| Realization / build | Substitute from binary cache or build required derivations | Unavailable substitutes, unsupported system/package (`meta.platforms`), upstream build failures. | +| Shell initialization | Populate environment variables, run package setup hooks, run `shellHook` | Broken `shellHook` quoting, non-zero exit in a hook, `exec` replacing the shell and breaking `--command` / direnv capture. | +| Compilation / build inside shell | Run the project's compiler, linker, or build tool inside the realized shell | Missing headers (`.dev` output not selected), missing libraries, missing `pkg-config` when build queries `.pc`, compiler hardening flags rejecting code, wrong compiler/stdenv. | +| Runtime inside shell | Run compiled binaries, tests, or downloaded tools | Dynamic linker / ELF interpreter missing on NixOS for prebuilt Linux binaries, missing runtime shared libraries, host state differences. | + +`Established`: evaluation success does not prove realization, shell startup, compilation, or +runtime behavior. + +## 2. Progressive validation levels + +Pick the commands that match the project's workflow (`nix develop` for a flake, `nix-shell` for +`shell.nix`). Run applicable levels in order: + +| Level | Example commands | What it proves | What it does NOT prove | +|---|---|---|---| +| 1. Evaluation | `nix flake show`; `nix eval .#devShells..default.drvPath`; `nix-instantiate shell.nix` | Expression parses and produces a derivation for that system | That inputs can be fetched/built, that the shell starts, or that other systems evaluate | +| 2. Realization + shell start | `nix develop --command true`; `nix-shell --run true` | Required store paths exist on this host and the shell initializes for command mode | That tools have expected versions, that interactive prompts work, or that the project builds | +| 3. Environment check | `nix develop --command sh -c 'command -v && --version'`; `nix develop --command printenv `; `pkg-config --modversion ` (only if the build uses `pkg-config`) | Named tools, versions, and variables are present in the shell on this host | That compilation, linking, or project commands succeed | +| 4. Project command | `nix develop --command ` (or `nix-shell --run ...`) | That specific command succeeded on this host with current inputs | Other commands, other target systems, or unpinned ecosystem downloads | + +### Where `nix flake check` fits + +`Established` (Nix 2.35 `nix flake check` manual): `nix flake check` evaluates recognized flake +outputs and builds derivations in `checks.`. It does **not** enter `devShells` or run +project build commands unless a check derivation explicitly does so. Report it as an output/check +validation, never as proof that the devShell starts or compiles the project. + +### Reporting rules and blocked checks + +- Report every level as `passed`, `failed`, `blocked`, or `not run`. +- For `passed` and `failed`, include the exact command run and a concise excerpt of the observed + output. Never report a command that was not executed in this session. +- **Untracked files in Git-backed flakes**: when a newly created `flake.nix` or imported local + file is untracked, Git-filtered flake evaluation cannot see it. + - Do **not** run `git add` (staging belongs to the user / `git-commit`). + - Do **not** substitute `path:.` by default (it bypasses Git source filtering, copies the whole + directory including untracked files into the Nix store, and does not test what contributors + will run). + - Mark the flake-dependent levels as `blocked: is untracked, so Git-filtered flake + evaluation omits it`. + - Still run any check that does not depend on the untracked flake (static review of the file, + syntax check with `nix-instantiate --parse `, or validation of an existing `shell.nix`), + and state clearly that parsing does not prove evaluation, realization, or runtime. + - Under **User actions**, ask the user to track the file (manually or via `git-commit`) and + rerun the blocked levels. + +## 3. Symptom-to-evidence table + +Treat symptoms as hypotheses. Inspect first, then make the smallest justified change. + +| Symptom | Phase | What to inspect first | Smallest next step | +|---|---|---|---| +| Flake says a visible local file does not exist | Evaluation | `git status` (is the path untracked?) | Explain Git source filtering; do not stage; ask user to track the path (or use `git-commit`). | +| `experimental Nix feature 'nix-command' / 'flakes' is disabled` | CLI / Evaluation | `nix --version`, `/etc/nix/nix.conf`, `~/.config/nix/nix.conf`, project docs | Follow the project's documented invocation or use classic `shell.nix` if supported. | +| `attribute 'devShells..default' missing` or unsupported system | Evaluation / Realization | Flake outputs and package `meta.platforms` in pinned nixpkgs | Add only required systems; wrap OS-specific packages in `lib.optionals`. | +| `cannot coerce a function to a string` in package list | Evaluation | Error trace and the `packages` / `buildInputs` list syntax | Parenthesize function application inside lists (`(pkgs.foo.withPackages ...)`), or pass required args. | +| Unfree package rejected | Evaluation | Exact package name in trace and repo unfree policy | Ask the user or follow existing repo config; never enable `allowUnfree` silently. | +| Header (`.h`) or library (`-l...`) not found | Compilation | Build log, compiler command, package `outputs` in pinned nixpkgs, whether build calls `pkg-config` or CMake | See [native-deps.md](native-deps.md): add the missing library to `buildInputs`, select `.dev` if required, and add `pkg-config` to `nativeBuildInputs` only if the build queries `.pc` files. | +| Build fails with `-Werror=format-security` or similar wrapper flag | Compilation | Exact compiler error and active hardening flags | Narrowly disable the specific flag (for example `hardeningDisable = [ "format" ];` after checking pinned nixpkgs), not `all`. | +| `clang` added to `packages` but `cc` is still GCC | Compilation | `nix develop --command which cc` and `echo $CC` | Standard `mkShell` stdenv supplies `CC`; see compiler override in [native-deps.md](native-deps.md#selecting-a-compiler). | +| Prebuilt Linux binary fails with `No such file or directory` or missing `.so` on NixOS | Runtime | `file `, `patchelf --print-interpreter `, `ldd ` | Diagnose interpreter vs shared libs vs FHS paths using [native-deps.md](native-deps.md#foreign-binaries-on-nixos). | +| `nix develop --command ` opens an interactive shell or ignores ``, or direnv fails | Shell initialization | `shellHook` contents (especially `exec ` or unconditional stdout noise) | Remove `exec` or guard interactive-only commands; keep existing working hook lines intact. | +| Slow evaluation or multiple `nixpkgs` copies in `flake.lock` | Evaluation | `nix flake metadata` input graph | Remove unused inputs; add `.follows = "nixpkgs"` only where sharing the root pin is compatible and intended. | +| `nix develop` fails on a custom raw derivation | Shell initialization | Derivation attributes and expected builder environment | Prefer `pkgs.mkShell` / `pkgs.mkShellNoCC` for nixpkgs packages. |