From 02ec5c27e2017145be693866914e39fea36e29e1 Mon Sep 17 00:00:00 2001 From: rahul Date: Wed, 28 Oct 2026 17:14:31 +0000 Subject: [PATCH 1/5] Add pinned flake toolchain and shell outputs Assisted-by: Replit --- README.md | 64 +++++++++++++ flake.nix | 5 + pkgs/bundle/default.nix | 6 +- pkgs/default.nix | 4 +- pkgs/moduleit/entrypoint.nix | 23 ++++- pkgs/moduleit/module-definition.nix | 8 +- pkgs/moduleit/shell-package.nix | 41 ++++++++ pkgs/modules/default.nix | 15 +-- pkgs/toolchain/default.nix | 56 +++++++++++ pkgs/toolchain/tests.nix | 141 ++++++++++++++++++++++++++++ scripts/ci_check.sh | 1 + 11 files changed, 341 insertions(+), 23 deletions(-) create mode 100644 pkgs/moduleit/shell-package.nix create mode 100644 pkgs/toolchain/default.nix create mode 100644 pkgs/toolchain/tests.nix diff --git a/README.md b/README.md index 635ab5a8..f0476ca2 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,70 @@ the Node.js 24 major that the SvelteKit module already used. ## Building +### Pinned shell and toolchain outputs + +Existing module packages still build the same JSON files. The additive +`shellPackages.x86_64-linux` and `deploymentShellPackages.x86_64-linux` maps +expose setup-hook packages under the same IDs, including aliases and compatibility +modules. The corresponding buildable package names are literal `shell.` and +`deployment-shell.` keys; for example: + +``` +nix build '.#packages.x86_64-linux."shell.python-3.12"' +``` + +Use a locked nixmodules input without overriding or following any of its inputs. +Aliases resolve within that pin; they do not promise the runtime version named by +a retired ID. Pin changes require checking the resolved module paths, not just +the requested IDs or display versions. + +```nix +outputs = { nixpkgs, nixmodules, ... }: + let + toolchain = nixmodules.lib.mkToolchain { + moduleIds = [ "replit" "nodejs-24" "python-base-3.13" ]; + deployment = false; + }; + in { + packages.x86_64-linux.toolchain = toolchain; + devShells.x86_64-linux.default = nixpkgs.legacyPackages.x86_64-linux.mkShell { + packages = [ toolchain.shellPackage ]; + }; + }; +``` + +`lib.mkToolchain { moduleIds; deployment ? false; }` builds a directory containing: + +* `modules.json`: an object keyed by each requested ID, containing the complete, + unchanged module JSON. Environment references such as `$REPL_HOME` remain literal. +* `metadata.json`: `{ schemaVersion = 1; system; moduleIds; deployment; + resolvedModules; }`. The two arrays retain caller order. Each resolved entry + contains `id` (requested ID), `moduleId` (implementation ID), `modulePath` + (module JSON store path), and `shellPath` (module shell-package store path). +* `shell`: a symlink to the aggregate setup-hook package, also exposed as the + derivation's `shellPackage` attribute. + +The directory's closure retains the selected runtime and IDE dependencies, +including tools referenced only by command paths in the JSON. It does not merge +user configuration, select default modules, or activate an environment. Supply +every desired module explicitly. Unknown or duplicate IDs fail evaluation. +Consumers must bind these outputs to their exact source and lockfile and verify +the realized closure separately; `metadata.json` is not a provenance attestation. + +For shells, environment keys use last-module-wins order, while module PATH values +are concatenated in selection order before the inherited PATH. Setup hooks expand +`$NAME` and `${NAME}` references without evaluating shell commands, resolve +dependencies between environment keys, and reject cycles. `REPL_HOME` defaults to +the shell's working directory when unset. These hooks run in `nix develop` and +`nix-shell`, not `nix shell` or `nix profile`. Runtime consumers still apply their +own dynamic-variable expansion and configuration precedence to `modules.json`. + +`lib.mkBundle { moduleIds; deployment ? false; }` retains the existing +`etc/nixmodules/modules.json` path-index layout and rejects unknown IDs. Omitting +`moduleIds` includes the complete selected development or deployment map. +Keep generated project flakes in a small dedicated directory rather than copying +the entire project tree into the flake source. + For each of the following examples, the build result will be found in a file or directory named `result`. To build the full bundle, including compatibility modules (this will take a while, and a lot of disk space): diff --git a/flake.nix b/flake.nix index 6ebe2d3b..1b093df9 100644 --- a/flake.nix +++ b/flake.nix @@ -181,6 +181,11 @@ packages.x86_64-linux = import ./pkgs { inherit pkgs self; }; + shellPackages.x86_64-linux = pkgs.lib.mapAttrs (_: module: module.shellPackage) self.modules; + deploymentShellPackages.x86_64-linux = pkgs.lib.mapAttrs (_: module: module.shellPackage) self.deploymentModules; + lib.mkBundle = pkgs.callPackage ./pkgs/bundle { inherit self; }; + lib.mkToolchain = import ./pkgs/toolchain { inherit pkgs self; }; + checks.x86_64-linux.flake-toolchain = import ./pkgs/toolchain/tests.nix { inherit pkgs; }; checks.x86_64-linux.module-registry = assert import ./scripts/module-registry-test.nix; assert builtins.attrNames self.modules == builtins.attrNames self.deploymentModules; diff --git a/pkgs/bundle/default.nix b/pkgs/bundle/default.nix index 7338603d..642f3503 100644 --- a/pkgs/bundle/default.nix +++ b/pkgs/bundle/default.nix @@ -11,13 +11,13 @@ { pkgs, lib, self, ... }: with builtins; with pkgs.lib; -{ moduleIds ? null }: +{ moduleIds ? null, deployment ? false }: let - modules = self.modules; + modules = if deployment then self.deploymentModules else self.modules; filteredModules = if moduleIds == null then modules else - filterAttrs (moduleId: _: elem moduleId moduleIds) modules; + genAttrs moduleIds (id: modules.${id} or (throw "Unknown nixmodule: ${id}")); modulesMap = mapAttrs (name: drv: { path = drv.outPath; diff --git a/pkgs/default.nix b/pkgs/default.nix index 95f7adc6..9b02a267 100644 --- a/pkgs/default.nix +++ b/pkgs/default.nix @@ -100,4 +100,6 @@ rec { deploymentModules = self.deploymentModules; } - // modules +// modules +// mapAttrs' (id: module: nameValuePair "shell.${id}" module.shellPackage) self.modules + // mapAttrs' (id: module: nameValuePair "deployment-shell.${id}" module.shellPackage) self.deploymentModules diff --git a/pkgs/moduleit/entrypoint.nix b/pkgs/moduleit/entrypoint.nix index 964d74b7..42469530 100644 --- a/pkgs/moduleit/entrypoint.nix +++ b/pkgs/moduleit/entrypoint.nix @@ -16,8 +16,23 @@ let modulesPath = builtins.toString ./.; }; }); + result = + if deployment then module.config.replit.buildDeploymentModule + else module.config.replit.buildModule; + packages = module.config.replit.packages + ++ pkgs.lib.optionals (!deployment) module.config.replit.dev.packages; in -if deployment then - module.config.replit.buildDeploymentModule -else - module.config.replit.buildModule +pkgs.lib.lazyDerivation { + derivation = result; + passthru = { + moduleId = module.config.id; + moduleConfig = result.moduleConfig; + runtimePackages = packages; + shellPackage = pkgs.callPackage ./shell-package.nix { + name = "replit-${if deployment then "deployment-" else ""}shell-${module.config.id}"; + inherit packages; + env = result.moduleConfig.env; + passthru.module = result; + }; + }; +} diff --git a/pkgs/moduleit/module-definition.nix b/pkgs/moduleit/module-definition.nix index d0528f67..e361a066 100644 --- a/pkgs/moduleit/module-definition.nix +++ b/pkgs/moduleit/module-definition.nix @@ -718,7 +718,9 @@ in }; in - pkgs.writeText "replit-module-${config.id}" (builtins.toJSON moduleJSON); + pkgs.writeText "replit-module-${config.id}" (builtins.toJSON moduleJSON) // { + moduleConfig = moduleJSON; + }; replit.buildDeploymentModule = let @@ -746,6 +748,8 @@ in }; in - pkgs.writeText "replit-deployment-module-${config.id}" (builtins.toJSON moduleJSON); + pkgs.writeText "replit-deployment-module-${config.id}" (builtins.toJSON moduleJSON) // { + moduleConfig = moduleJSON; + }; }; } diff --git a/pkgs/moduleit/shell-package.nix b/pkgs/moduleit/shell-package.nix new file mode 100644 index 00000000..d3472e60 --- /dev/null +++ b/pkgs/moduleit/shell-package.nix @@ -0,0 +1,41 @@ +{ lib +, makeSetupHook +, writeText +, name +, packages +, env +, passthru ? { } +}: +let + variablePattern = "[a-zA-Z_][a-zA-Z0-9_]*"; + splitValue = value: builtins.split "[$]([{]${variablePattern}[}]|${variablePattern})" value; + variableName = match: lib.removeSuffix "}" (lib.removePrefix "{" (builtins.head match)); + references = value: map variableName (builtins.filter builtins.isList (splitValue value)); + names = builtins.attrNames env; + ordered = lib.toposort + (a: b: a != b && builtins.elem a (references env.${b})) + names; + # Expand only environment references, never shell substitutions or operators. + shellValue = value: lib.concatMapStrings + (part: + if builtins.isString part then lib.escapeShellArg part + else "\"\${${variableName part}-}\"") + (splitValue value); + hook = + assert lib.assertMsg + (builtins.all (key: builtins.match variablePattern key != null) names) + "Module environment keys must be shell variable names"; + assert lib.assertMsg (!(ordered ? cycle)) "Module environment contains a variable cycle"; + '' + export REPL_HOME="''${REPL_HOME:-$PWD}" + '' + lib.concatMapStringsSep "\n" + (key: "export ${key}=${shellValue env.${key}}" + + lib.optionalString (key == "PATH") "\${PATH:+:}\"$PATH\"") + ordered.result + "\n"; +in +makeSetupHook +{ + inherit name passthru; + propagatedBuildInputs = packages; +} + (writeText "${name}-hook" hook) diff --git a/pkgs/modules/default.nix b/pkgs/modules/default.nix index e41837c4..b4615964 100644 --- a/pkgs/modules/default.nix +++ b/pkgs/modules/default.nix @@ -192,19 +192,8 @@ let modules = apply-upgrade-map (developmentModuleSet allModulesList); deploymentModules = apply-upgrade-map (deploymentModuleSet allModulesList); - get-module-id = - module: - let - match = builtins.match "^\/nix\/store\/([^-]+)-replit-module-(.+)$" module.outPath; - in - builtins.elemAt match 1; - - get-deployment-module-id = - module: - let - match = builtins.match "^\/nix\/store\/([^-]+)-replit-deployment-module-(.+)$" module.outPath; - in - builtins.elemAt match 1; + get-module-id = module: module.moduleId; + get-deployment-module-id = module: module.moduleId; in { inherit diff --git a/pkgs/toolchain/default.nix b/pkgs/toolchain/default.nix new file mode 100644 index 00000000..2cb853aa --- /dev/null +++ b/pkgs/toolchain/default.nix @@ -0,0 +1,56 @@ +{ pkgs, self }: +{ moduleIds +, deployment ? false +}: +let + inherit (pkgs) lib; + available = if deployment then self.deploymentModules else self.modules; + selected = map + (id: available.${id} or (throw "Unknown nixmodule: ${id}")) + moduleIds; + env = lib.foldl' + (acc: module: + let + next = module.moduleConfig.env; + paths = builtins.filter (path: path != "") [ (acc.PATH or "") (next.PATH or "") ]; + in + acc // next // { PATH = lib.concatStringsSep ":" paths; }) + { } + selected; + shellPackage = pkgs.callPackage ../moduleit/shell-package.nix { + name = "replit-toolchain-shell"; + inherit env; + packages = lib.concatMap (module: module.runtimePackages) selected; + }; + moduleConfigs = builtins.listToAttrs (lib.zipListsWith + (id: module: { name = id; value = module.moduleConfig; }) + moduleIds + selected); + metadata = { + schemaVersion = 1; + system = pkgs.stdenv.hostPlatform.system; + inherit moduleIds deployment; + resolvedModules = lib.zipListsWith + (id: module: { + inherit id; + moduleId = module.moduleId; + modulePath = module.outPath; + shellPath = module.shellPackage.outPath; + }) + moduleIds + selected; + }; +in +assert lib.assertMsg + (builtins.isList moduleIds && builtins.all builtins.isString moduleIds) + "moduleIds must be a list of strings"; +assert lib.assertMsg + (builtins.length moduleIds == builtins.length (lib.unique moduleIds)) + "Duplicate nixmodule IDs"; +(pkgs.linkFarm "replit-toolchain" [ + { name = "modules.json"; path = pkgs.writeText "modules.json" (builtins.toJSON moduleConfigs); } + { name = "metadata.json"; path = pkgs.writeText "metadata.json" (builtins.toJSON metadata); } + { name = "shell"; path = shellPackage; } +]) // { + inherit shellPackage moduleConfigs metadata; +} diff --git a/pkgs/toolchain/tests.nix b/pkgs/toolchain/tests.nix new file mode 100644 index 00000000..477d9da5 --- /dev/null +++ b/pkgs/toolchain/tests.nix @@ -0,0 +1,141 @@ +{ pkgs }: +let + inherit (pkgs) lib; + runtime = pkgs.runCommand "toolchain-test-runtime" { } '' + mkdir -p "$out/bin" + printf '#!/bin/sh\nexit 0\n' > "$out/bin/runtime" + chmod +x "$out/bin/runtime" + ''; + ide = pkgs.writeText "toolchain-test-ide" "IDE-only dependency"; + definition = { + id = "fixture"; + name = "Fixture"; + replit = { + packages = [ runtime ]; + env = { + A_DEPENDENT = "$Z_BASE/child"; + Z_BASE = "$REPL_HOME/base"; + BRACED = "\${Z_BASE}/braced"; + LITERAL = "$(touch /tmp/nixmodules-shell-injection) `false` \" ' \\"; + MODE = "deployment"; + PATH = "$Z_BASE/bin"; + }; + runners.fixture = { + name = "Fixture"; + language = "fixture"; + start = "${runtime}/bin/runtime $file"; + }; + dev = { + env.MODE = "development"; + languageServers.fixture = { + name = "Fixture server"; + language = "fixture"; + start = "${ide} $file"; + }; + }; + }; + }; + mkModule = deployment: configPath: pkgs.callPackage ../moduleit/entrypoint.nix { + inherit deployment configPath; + pkgs-23_05 = pkgs; + pkgs-24_11 = pkgs; + }; + development = mkModule false definition; + deployment = mkModule true definition; + applyAliases = import ../upgrade-map/apply.nix { alias = "fixture"; }; + self = { + modules = applyAliases { + fixture = development; + override = mkModule false { + id = "override"; + name = "Override"; + replit.env.MODE = "last"; + }; + }; + deploymentModules = applyAliases { fixture = deployment; }; + }; + mkToolchain = import ./default.nix { inherit pkgs self; }; + mkBundle = pkgs.callPackage ../bundle { inherit self; }; + toolchain = mkToolchain { moduleIds = [ "fixture" "alias" ]; }; + overridden = mkToolchain { moduleIds = [ "alias" "override" ]; }; + deploymentToolchain = mkToolchain { moduleIds = [ "fixture" ]; deployment = true; }; + closure = pkgs.closureInfo { rootPaths = [ toolchain ]; }; + deploymentClosure = pkgs.closureInfo { rootPaths = [ deploymentToolchain ]; }; + fails = value: !(builtins.tryEval (builtins.deepSeq value true)).success; + lazyModule = mkModule false { + id = "lazy"; + name = "Lazy"; + replit.packages = throw "moduleId must not evaluate packages or output paths"; + }; + cycle = pkgs.callPackage ../moduleit/shell-package.nix { + name = "cycle"; + packages = [ ]; + env = { A = "$B"; B = "$A"; }; + }; + shellSmoke = pkgs.runCommand "toolchain-shell-check" + { + nativeBuildInputs = [ toolchain.shellPackage ]; + REPL_HOME = "/tmp/project with spaces"; + } '' + test "$MODE" = development + test "$A_DEPENDENT" = "$REPL_HOME/base/child" + test "$(command -v runtime)" = "${runtime}/bin/runtime" + touch "$out" + ''; +in +assert lazyModule.moduleId == "lazy"; +assert toolchain.metadata.moduleIds == [ "fixture" "alias" ]; +assert map (entry: entry.id) toolchain.metadata.resolvedModules == [ "fixture" "alias" ]; +assert map (entry: entry.moduleId) toolchain.metadata.resolvedModules == [ "fixture" "fixture" ]; +assert toolchain.moduleConfigs.alias == development.moduleConfig; +assert deploymentToolchain.moduleConfigs.fixture == deployment.moduleConfig; +assert deployment.moduleConfig.languageServers == { }; +assert development.moduleConfig.env.MODE == "development"; +assert deployment.moduleConfig.env.MODE == "deployment"; +assert fails (mkToolchain { moduleIds = [ "missing" ]; }).outPath; +assert fails (mkToolchain { moduleIds = [ "fixture" "fixture" ]; }).outPath; +assert fails (mkBundle { moduleIds = [ "missing" ]; }).outPath; +assert fails cycle.outPath; +pkgs.runCommand "flake-toolchain-check" +{ + nativeBuildInputs = [ pkgs.jq ]; +} '' + test -f ${shellSmoke} + test -d ${toolchain}/shell/nix-support + jq -e '.schemaVersion == 1 and .system == "x86_64-linux" + and .moduleIds == ["fixture", "alias"] and .deployment == false + and .resolvedModules[0].id == "fixture" + and .resolvedModules[0].moduleId == "fixture"' ${toolchain}/metadata.json + jq -e '.deployment == true and .moduleIds == ["fixture"]' ${deploymentToolchain}/metadata.json + jq -S . ${development} > expected.json + jq -S .alias ${toolchain}/modules.json > actual.json + cmp expected.json actual.json + jq -S . ${deployment} > expected.json + jq -S .fixture ${deploymentToolchain}/modules.json > actual.json + cmp expected.json actual.json + grep -Fx ${runtime} ${closure}/store-paths + grep -Fx ${ide} ${closure}/store-paths + if grep -Fx ${ide} ${deploymentClosure}/store-paths; then + echo "Deployment includes a development-only IDE dependency" >&2 + exit 1 + fi + ( + export REPL_HOME="/tmp/project with spaces" + export PATH="/original/path" + source ${toolchain}/shell/nix-support/setup-hook + test "$A_DEPENDENT" = "$REPL_HOME/base/child" + test "$BRACED" = "$REPL_HOME/base/braced" + test "$LITERAL" = ${lib.escapeShellArg definition.replit.env.LITERAL} + test "$MODE" = development + test "$PATH" = "$REPL_HOME/base/bin:${runtime}/bin:$REPL_HOME/base/bin:${runtime}/bin:/original/path" + ) + ( + source ${deployment.shellPackage}/nix-support/setup-hook + test "$MODE" = deployment + ) + ( + source ${overridden}/shell/nix-support/setup-hook + test "$MODE" = last + ) + touch "$out" +'' diff --git a/scripts/ci_check.sh b/scripts/ci_check.sh index 13dcab24..5a70c63d 100755 --- a/scripts/ci_check.sh +++ b/scripts/ci_check.sh @@ -17,6 +17,7 @@ nix eval "${NIX_FLAGS[@]}" --file scripts/module-registry-test.nix nix eval "${NIX_FLAGS[@]}" .#modules --json nix eval "${NIX_FLAGS[@]}" .#deploymentModules --json nix build "${NIX_FLAGS[@]}" .#checks.x86_64-linux.module-registry --no-link +nix build "${NIX_FLAGS[@]}" .#checks.x86_64-linux.flake-toolchain --no-link nix build "${NIX_FLAGS[@]}" .#checks.x86_64-linux.pip-user-site --no-link # The standalone lockfile OCI helper reconstructs old bundles, not current implementations. From c363fc46145868db0d631a489906e0159159611a Mon Sep 17 00:00:00 2001 From: rahul Date: Wed, 28 Oct 2026 17:20:41 +0000 Subject: [PATCH 2/5] Preserve legacy bundle filtering in the opt-in API Assisted-by: Replit --- README.md | 2 ++ flake.nix | 2 +- pkgs/bundle/api.nix | 9 +++++++++ pkgs/bundle/default.nix | 2 +- pkgs/toolchain/tests.nix | 14 +++++++++++++- 5 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 pkgs/bundle/api.nix diff --git a/README.md b/README.md index f0476ca2..7fbf6e0e 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,8 @@ own dynamic-variable expansion and configuration precedence to `modules.json`. `lib.mkBundle { moduleIds; deployment ? false; }` retains the existing `etc/nixmodules/modules.json` path-index layout and rejects unknown IDs. Omitting `moduleIds` includes the complete selected development or deployment map. +This strict validation applies only to the new API; existing bundle callers +continue to filter out unknown IDs. Keep generated project flakes in a small dedicated directory rather than copying the entire project tree into the flake source. diff --git a/flake.nix b/flake.nix index 1b093df9..ceeff35b 100644 --- a/flake.nix +++ b/flake.nix @@ -183,7 +183,7 @@ }; shellPackages.x86_64-linux = pkgs.lib.mapAttrs (_: module: module.shellPackage) self.modules; deploymentShellPackages.x86_64-linux = pkgs.lib.mapAttrs (_: module: module.shellPackage) self.deploymentModules; - lib.mkBundle = pkgs.callPackage ./pkgs/bundle { inherit self; }; + lib.mkBundle = import ./pkgs/bundle/api.nix { inherit pkgs self; }; lib.mkToolchain = import ./pkgs/toolchain { inherit pkgs self; }; checks.x86_64-linux.flake-toolchain = import ./pkgs/toolchain/tests.nix { inherit pkgs; }; checks.x86_64-linux.module-registry = diff --git a/pkgs/bundle/api.nix b/pkgs/bundle/api.nix new file mode 100644 index 00000000..eaeba58b --- /dev/null +++ b/pkgs/bundle/api.nix @@ -0,0 +1,9 @@ +{ pkgs, self }: +{ moduleIds ? null, deployment ? false }: +let + modules = if deployment then self.deploymentModules else self.modules; +in +assert moduleIds == null || builtins.all + (id: builtins.hasAttr id modules || throw "Unknown nixmodule: ${id}") + moduleIds; +pkgs.callPackage ./default.nix { inherit self; } { inherit moduleIds deployment; } diff --git a/pkgs/bundle/default.nix b/pkgs/bundle/default.nix index 642f3503..c9303753 100644 --- a/pkgs/bundle/default.nix +++ b/pkgs/bundle/default.nix @@ -17,7 +17,7 @@ let filteredModules = if moduleIds == null then modules else - genAttrs moduleIds (id: modules.${id} or (throw "Unknown nixmodule: ${id}")); + filterAttrs (moduleId: _: elem moduleId moduleIds) modules; modulesMap = mapAttrs (name: drv: { path = drv.outPath; diff --git a/pkgs/toolchain/tests.nix b/pkgs/toolchain/tests.nix index 477d9da5..ae0b491a 100644 --- a/pkgs/toolchain/tests.nix +++ b/pkgs/toolchain/tests.nix @@ -55,7 +55,9 @@ let deploymentModules = applyAliases { fixture = deployment; }; }; mkToolchain = import ./default.nix { inherit pkgs self; }; - mkBundle = pkgs.callPackage ../bundle { inherit self; }; + legacyBundle = pkgs.callPackage ../bundle { inherit self; }; + mkBundle = import ../bundle/api.nix { inherit pkgs self; }; + deploymentBundle = mkBundle { moduleIds = [ "alias" ]; deployment = true; }; toolchain = mkToolchain { moduleIds = [ "fixture" "alias" ]; }; overridden = mkToolchain { moduleIds = [ "alias" "override" ]; }; deploymentToolchain = mkToolchain { moduleIds = [ "fixture" ]; deployment = true; }; @@ -95,12 +97,22 @@ assert deployment.moduleConfig.env.MODE == "deployment"; assert fails (mkToolchain { moduleIds = [ "missing" ]; }).outPath; assert fails (mkToolchain { moduleIds = [ "fixture" "fixture" ]; }).outPath; assert fails (mkBundle { moduleIds = [ "missing" ]; }).outPath; +assert fails (mkBundle { moduleIds = [ "fixture" "missing" ]; }).outPath; +assert fails (mkBundle { moduleIds = [ "missing" ]; deployment = true; }).outPath; +assert (legacyBundle { moduleIds = [ "fixture" "missing" ]; }).outPath + == (legacyBundle { moduleIds = [ "fixture" ]; }).outPath; +assert (legacyBundle { moduleIds = [ "missing" ]; }).outPath + == (legacyBundle { moduleIds = [ ]; }).outPath; +assert (legacyBundle { moduleIds = [ "alias" "missing" ]; deployment = true; }).outPath + == deploymentBundle.outPath; assert fails cycle.outPath; pkgs.runCommand "flake-toolchain-check" { nativeBuildInputs = [ pkgs.jq ]; } '' test -f ${shellSmoke} + test "$(readlink ${deploymentBundle}/alias)" = "${deployment}" + jq -e --arg path "${deployment}" '.alias.path == $path' ${deploymentBundle}/etc/nixmodules/modules.json test -d ${toolchain}/shell/nix-support jq -e '.schemaVersion == 1 and .system == "x86_64-linux" and .moduleIds == ["fixture", "alias"] and .deployment == false From 09aa7d0dd47d107cf6eb1e74ab70fc2dfb3b5974 Mon Sep 17 00:00:00 2001 From: rahul Date: Wed, 28 Oct 2026 20:55:17 +0000 Subject: [PATCH 3/5] Keep runtime dependencies out of compiler build hooks Assisted-by: Replit --- pkgs/moduleit/shell-package.nix | 15 ++++++++++----- pkgs/toolchain/tests.nix | 7 ++++++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/pkgs/moduleit/shell-package.nix b/pkgs/moduleit/shell-package.nix index d3472e60..1f310777 100644 --- a/pkgs/moduleit/shell-package.nix +++ b/pkgs/moduleit/shell-package.nix @@ -1,5 +1,5 @@ { lib -, makeSetupHook +, runCommand , writeText , name , packages @@ -33,9 +33,14 @@ let + lib.optionalString (key == "PATH") "\${PATH:+:}\"$PATH\"") ordered.result + "\n"; in -makeSetupHook +runCommand name { - inherit name passthru; - propagatedBuildInputs = packages; + inherit passthru; } - (writeText "${name}-hook" hook) + '' + mkdir -p "$out/nix-support" + cp ${writeText "${name}-hook" hook} "$out/nix-support/setup-hook" + # Keep runtime references without running their compiler build hooks. + printf '%s\n' ${lib.escapeShellArg (lib.concatMapStringsSep "\n" toString packages)} \ + > "$out/nix-support/runtime-dependencies" + '' diff --git a/pkgs/toolchain/tests.nix b/pkgs/toolchain/tests.nix index ae0b491a..d72b2d8a 100644 --- a/pkgs/toolchain/tests.nix +++ b/pkgs/toolchain/tests.nix @@ -2,9 +2,14 @@ let inherit (pkgs) lib; runtime = pkgs.runCommand "toolchain-test-runtime" { } '' - mkdir -p "$out/bin" + mkdir -p "$out/bin" "$out/nix-support" printf '#!/bin/sh\nexit 0\n' > "$out/bin/runtime" chmod +x "$out/bin/runtime" + cat > "$out/nix-support/setup-hook" <<'HOOK' + : "$NIX_CC" + echo "A runtime-only build hook was sourced" >&2 + return 1 + HOOK ''; ide = pkgs.writeText "toolchain-test-ide" "IDE-only dependency"; definition = { From 3cd3ac9c16845114cee14811ec99a2dca854563b Mon Sep 17 00:00:00 2001 From: rahul Date: Fri, 30 Oct 2026 01:33:10 +0000 Subject: [PATCH 4/5] Expose the producer-owned toolchain environment Reuse the shell setup-hook for a dependency-free env0 interface. Retain generated development, deployment and override fixtures for consumers. Document editable flakes and the unprivileged preparation boundary. Assisted-by: Replit --- README.md | 39 ++++++++++++++++++++++++-- pkgs/toolchain/default.nix | 8 ++++++ pkgs/toolchain/tests.nix | 57 +++++++++++++++++++++++++++++++++++++- 3 files changed, 101 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7fbf6e0e..f990cb54 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,9 @@ outputs = { nixpkgs, nixmodules, ... }: (module JSON store path), and `shellPath` (module shell-package store path). * `shell`: a symlink to the aggregate setup-hook package, also exposed as the derivation's `shellPackage` attribute. +* `bin/replit-toolchain-env`: prints the resolved module environment and + `REPL_HOME` as NUL-terminated `KEY=value` records, using the same setup hook + as the shell and Bash's built-in `printf`. The directory's closure retains the selected runtime and IDE dependencies, including tools referenced only by command paths in the JSON. It does not merge @@ -116,8 +119,40 @@ are concatenated in selection order before the inherited PATH. Setup hooks expan `$NAME` and `${NAME}` references without evaluating shell commands, resolve dependencies between environment keys, and reject cycles. `REPL_HOME` defaults to the shell's working directory when unset. These hooks run in `nix develop` and -`nix-shell`, not `nix shell` or `nix profile`. Runtime consumers still apply their -own dynamic-variable expansion and configuration precedence to `modules.json`. +`nix-shell`, not `nix shell` or `nix profile`. + +Runtime consumers should run `bin/replit-toolchain-env` in their unprivileged +preparation sandbox, with an explicit inherited environment and working directory, +instead of reimplementing module merging or expansion. Its output contains only +module-defined keys and `REPL_HOME`; other inherited variables are not copied. +The preparation baseline allows only `HOME`, `REPL_HOME`, `PWD`, `PATH`, +`LD_LIBRARY_PATH`, `REPLIT_LD_LIBRARY_PATH`, `PYTHONPATH` and `XDG_DATA_DIRS`, +with at most 64 KiB per value. Exclude secrets, `BASH_ENV`, `ENV` and other ambient +variables. The executable and setup hook are project-controlled code: run them +only in the UID 1000 preparation sandbox, never as root or on the host. +Limit captured output to 1 MiB and parse each NUL-terminated record at its first `=`; +reject malformed records, duplicate keys and invalid environment names. Empty values remain present +as `KEY=`; absent keys have no record. Newlines and `=` within values are preserved. +NUL cannot occur within an environment value. The records are sorted by key, while +their values retain module selection precedence. This is observed environment +data, not an authenticated attestation. +`nix print-dev-env` on `shellPackage` describes its build environment, not this +runtime contract. User configuration precedence and command placeholders such as +`$file` remain the consumer's responsibility. + +A project may expose this derivation as `packages.x86_64-linux.default` using local +imports and additional pinned flake inputs. The generated example is a starting +point, not a byte-exact format requirement. Consumers must snapshot and bind the +complete local source tree, lockfile and configuration, then validate the realized +output contract and closure. Hashing only `flake.nix` does not cover local imports. +Do not rewrite existing project flakes or update their pins during preparation. + +`nix build .#checks.x86_64-linux.flake-toolchain` retains small development, +deployment and override fixtures in its output directory. Each contains +`metadata.json`, `modules.json`, `environment-input.json`, `environment.env0` +and its decoded `environment.json`, generated by the real module/toolchain code +and environment executable. Consumer tests can use these files without building +the language runtimes. `lib.mkBundle { moduleIds; deployment ? false; }` retains the existing `etc/nixmodules/modules.json` path-index layout and rejects unknown IDs. Omitting diff --git a/pkgs/toolchain/default.nix b/pkgs/toolchain/default.nix index 2cb853aa..c44cfd9e 100644 --- a/pkgs/toolchain/default.nix +++ b/pkgs/toolchain/default.nix @@ -22,6 +22,13 @@ let inherit env; packages = lib.concatMap (module: module.runtimePackages) selected; }; + environmentProgram = pkgs.writeShellScript "replit-toolchain-env" '' + set -euo pipefail + source ${shellPackage}/nix-support/setup-hook + ${lib.concatMapStringsSep "\n" + (key: "printf '%s=%s\\0' ${lib.escapeShellArg key} \"\${${key}}\"") + (builtins.attrNames (env // { REPL_HOME = ""; }))} + ''; moduleConfigs = builtins.listToAttrs (lib.zipListsWith (id: module: { name = id; value = module.moduleConfig; }) moduleIds @@ -51,6 +58,7 @@ assert lib.assertMsg { name = "modules.json"; path = pkgs.writeText "modules.json" (builtins.toJSON moduleConfigs); } { name = "metadata.json"; path = pkgs.writeText "metadata.json" (builtins.toJSON metadata); } { name = "shell"; path = shellPackage; } + { name = "bin/replit-toolchain-env"; path = environmentProgram; } ]) // { inherit shellPackage moduleConfigs metadata; } diff --git a/pkgs/toolchain/tests.nix b/pkgs/toolchain/tests.nix index d72b2d8a..13a50cd0 100644 --- a/pkgs/toolchain/tests.nix +++ b/pkgs/toolchain/tests.nix @@ -22,6 +22,10 @@ let Z_BASE = "$REPL_HOME/base"; BRACED = "\${Z_BASE}/braced"; LITERAL = "$(touch /tmp/nixmodules-shell-injection) `false` \" ' \\"; + PYTHONPATH = "$PYTHONPATH/suffix"; + MISSING = "$NOT_PRESENT"; + EMPTY = ""; + MULTILINE = "first=line\nsecond=line"; MODE = "deployment"; PATH = "$Z_BASE/bin"; }; @@ -89,6 +93,24 @@ let test "$(command -v runtime)" = "${runtime}/bin/runtime" touch "$out" ''; + environmentInput = { + REPL_HOME = "/tmp/project with spaces"; + PATH = "/original/path"; + PYTHONPATH = "/inherited"; + }; + environmentArgs = lib.concatStringsSep " " + (lib.mapAttrsToList (key: value: lib.escapeShellArg "${key}=${value}") environmentInput); + decodeEnvironment = '' + split("\u0000") + | if last != "" then error("Missing trailing NUL") else .[:-1] end + | map(index("=") as $separator | {key: .[:$separator], value: .[$separator + 1:]}) + | from_entries + ''; + fixtures = { + development = toolchain; + deployment = deploymentToolchain; + override = overridden; + }; in assert lazyModule.moduleId == "lazy"; assert toolchain.metadata.moduleIds == [ "fixture" "alias" ]; @@ -132,6 +154,10 @@ pkgs.runCommand "flake-toolchain-check" cmp expected.json actual.json grep -Fx ${runtime} ${closure}/store-paths grep -Fx ${ide} ${closure}/store-paths + if grep -Fx ${pkgs.jq} ${closure}/store-paths; then + echo "Toolchain includes a JSON encoder dependency" + exit 1 + fi if grep -Fx ${ide} ${deploymentClosure}/store-paths; then echo "Deployment includes a development-only IDE dependency" >&2 exit 1 @@ -154,5 +180,34 @@ pkgs.runCommand "flake-toolchain-check" source ${overridden}/shell/nix-support/setup-hook test "$MODE" = last ) - touch "$out" + ${lib.concatStringsSep "\n" (lib.mapAttrsToList (name: fixture: '' + mkdir -p "$out/${name}" + cp ${fixture}/metadata.json "$out/${name}/metadata.json" + cp ${fixture}/modules.json "$out/${name}/modules.json" + cp ${pkgs.writeText "environment-input.json" (builtins.toJSON environmentInput)} "$out/${name}/environment-input.json" + env -i ${environmentArgs} UNRELATED=not-exported \ + ${fixture}/bin/replit-toolchain-env > "$out/${name}/environment.env0" + jq -RsS ${lib.escapeShellArg decodeEnvironment} "$out/${name}/environment.env0" \ + > "$out/${name}/environment.json" + jq -e --arg literal ${lib.escapeShellArg definition.replit.env.LITERAL} ' + .REPL_HOME == "/tmp/project with spaces" + and .A_DEPENDENT == "/tmp/project with spaces/base/child" + and .BRACED == "/tmp/project with spaces/base/braced" + and .PYTHONPATH == "/inherited/suffix" + and .MISSING == "" + and .EMPTY == "" + and .MULTILINE == "first=line\nsecond=line" + and .LITERAL == $literal + and (has("UNRELATED") | not) + and (has("HOME") | not) + ' "$out/${name}/environment.json" + '') fixtures)} + jq -e --arg path "/tmp/project with spaces/base/bin:${runtime}/bin:/tmp/project with spaces/base/bin:${runtime}/bin:/original/path" \ + '.MODE == "development" and .PATH == $path' "$out/development/environment.json" + jq -e --arg path "/tmp/project with spaces/base/bin:${runtime}/bin:/original/path" \ + '.MODE == "deployment" and .PATH == $path' "$out/deployment/environment.json" + jq -e '.MODE == "last"' "$out/override/environment.json" + env -i PATH="" ${toolchain}/bin/replit-toolchain-env \ + | jq -RsS ${lib.escapeShellArg decodeEnvironment} > fallback-environment.json + jq -e --arg home "$PWD" '.REPL_HOME == $home and .PYTHONPATH == "/suffix"' fallback-environment.json '' From 1bbb7768080f17dbbdb78742bde0cb39ebac38b1 Mon Sep 17 00:00:00 2001 From: rahul Date: Fri, 30 Oct 2026 18:38:22 +0000 Subject: [PATCH 5/5] Remove README changes from the toolchain API PR Restore the README from the base branch without changing code, tests or package pins. Assisted-by: Replit --- README.md | 101 ------------------------------------------------------ 1 file changed, 101 deletions(-) diff --git a/README.md b/README.md index f990cb54..635ab5a8 100644 --- a/README.md +++ b/README.md @@ -61,107 +61,6 @@ the Node.js 24 major that the SvelteKit module already used. ## Building -### Pinned shell and toolchain outputs - -Existing module packages still build the same JSON files. The additive -`shellPackages.x86_64-linux` and `deploymentShellPackages.x86_64-linux` maps -expose setup-hook packages under the same IDs, including aliases and compatibility -modules. The corresponding buildable package names are literal `shell.` and -`deployment-shell.` keys; for example: - -``` -nix build '.#packages.x86_64-linux."shell.python-3.12"' -``` - -Use a locked nixmodules input without overriding or following any of its inputs. -Aliases resolve within that pin; they do not promise the runtime version named by -a retired ID. Pin changes require checking the resolved module paths, not just -the requested IDs or display versions. - -```nix -outputs = { nixpkgs, nixmodules, ... }: - let - toolchain = nixmodules.lib.mkToolchain { - moduleIds = [ "replit" "nodejs-24" "python-base-3.13" ]; - deployment = false; - }; - in { - packages.x86_64-linux.toolchain = toolchain; - devShells.x86_64-linux.default = nixpkgs.legacyPackages.x86_64-linux.mkShell { - packages = [ toolchain.shellPackage ]; - }; - }; -``` - -`lib.mkToolchain { moduleIds; deployment ? false; }` builds a directory containing: - -* `modules.json`: an object keyed by each requested ID, containing the complete, - unchanged module JSON. Environment references such as `$REPL_HOME` remain literal. -* `metadata.json`: `{ schemaVersion = 1; system; moduleIds; deployment; - resolvedModules; }`. The two arrays retain caller order. Each resolved entry - contains `id` (requested ID), `moduleId` (implementation ID), `modulePath` - (module JSON store path), and `shellPath` (module shell-package store path). -* `shell`: a symlink to the aggregate setup-hook package, also exposed as the - derivation's `shellPackage` attribute. -* `bin/replit-toolchain-env`: prints the resolved module environment and - `REPL_HOME` as NUL-terminated `KEY=value` records, using the same setup hook - as the shell and Bash's built-in `printf`. - -The directory's closure retains the selected runtime and IDE dependencies, -including tools referenced only by command paths in the JSON. It does not merge -user configuration, select default modules, or activate an environment. Supply -every desired module explicitly. Unknown or duplicate IDs fail evaluation. -Consumers must bind these outputs to their exact source and lockfile and verify -the realized closure separately; `metadata.json` is not a provenance attestation. - -For shells, environment keys use last-module-wins order, while module PATH values -are concatenated in selection order before the inherited PATH. Setup hooks expand -`$NAME` and `${NAME}` references without evaluating shell commands, resolve -dependencies between environment keys, and reject cycles. `REPL_HOME` defaults to -the shell's working directory when unset. These hooks run in `nix develop` and -`nix-shell`, not `nix shell` or `nix profile`. - -Runtime consumers should run `bin/replit-toolchain-env` in their unprivileged -preparation sandbox, with an explicit inherited environment and working directory, -instead of reimplementing module merging or expansion. Its output contains only -module-defined keys and `REPL_HOME`; other inherited variables are not copied. -The preparation baseline allows only `HOME`, `REPL_HOME`, `PWD`, `PATH`, -`LD_LIBRARY_PATH`, `REPLIT_LD_LIBRARY_PATH`, `PYTHONPATH` and `XDG_DATA_DIRS`, -with at most 64 KiB per value. Exclude secrets, `BASH_ENV`, `ENV` and other ambient -variables. The executable and setup hook are project-controlled code: run them -only in the UID 1000 preparation sandbox, never as root or on the host. -Limit captured output to 1 MiB and parse each NUL-terminated record at its first `=`; -reject malformed records, duplicate keys and invalid environment names. Empty values remain present -as `KEY=`; absent keys have no record. Newlines and `=` within values are preserved. -NUL cannot occur within an environment value. The records are sorted by key, while -their values retain module selection precedence. This is observed environment -data, not an authenticated attestation. -`nix print-dev-env` on `shellPackage` describes its build environment, not this -runtime contract. User configuration precedence and command placeholders such as -`$file` remain the consumer's responsibility. - -A project may expose this derivation as `packages.x86_64-linux.default` using local -imports and additional pinned flake inputs. The generated example is a starting -point, not a byte-exact format requirement. Consumers must snapshot and bind the -complete local source tree, lockfile and configuration, then validate the realized -output contract and closure. Hashing only `flake.nix` does not cover local imports. -Do not rewrite existing project flakes or update their pins during preparation. - -`nix build .#checks.x86_64-linux.flake-toolchain` retains small development, -deployment and override fixtures in its output directory. Each contains -`metadata.json`, `modules.json`, `environment-input.json`, `environment.env0` -and its decoded `environment.json`, generated by the real module/toolchain code -and environment executable. Consumer tests can use these files without building -the language runtimes. - -`lib.mkBundle { moduleIds; deployment ? false; }` retains the existing -`etc/nixmodules/modules.json` path-index layout and rejects unknown IDs. Omitting -`moduleIds` includes the complete selected development or deployment map. -This strict validation applies only to the new API; existing bundle callers -continue to filter out unknown IDs. -Keep generated project flakes in a small dedicated directory rather than copying -the entire project tree into the flake source. - For each of the following examples, the build result will be found in a file or directory named `result`. To build the full bundle, including compatibility modules (this will take a while, and a lot of disk space):