fix(nix): expose installed profile commands on PATH
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-10-01 14:30:47 -07:00
parent 409092fd05
commit 0182bdd3e2
12 changed files with 241 additions and 31 deletions

View file

@ -5,6 +5,17 @@ this file is the curated, human-readable summary.
## Unreleased — Fast defaults with user-controlled source builds ## Unreleased — Fast defaults with user-controlled source builds
- **Nix commands available after installation (2026-10-01).** `sys install
cmatrix --legacy --nix` now installs into a persistent shared Nix profile
instead of only realising a temporary shell. Phoebus adds both the shared
profile and the normal user's XDG Nix profile to `PATH` before starting the
Mango desktop, imports that path into the user manager, and verifies the
installed profile and executable names. `nix prepare` remains the temporary
realisation action. The existing playground was updated and passed an
installed-system VM boot with real `cmatrix` install, executable, shell PATH,
inventory and session-script checks (9/9). A fresh ISO/install has not yet
included this change.
- **Visible package operations and lane reliability (2026-10-01).** Human - **Visible package operations and lane reliability (2026-10-01).** Human
`sys` sessions stream package-manager output while commands run, including `sys` sessions stream package-manager output while commands run, including
Portage compilation, Flatpak progress, Snap changes, Nix realisation, Portage compilation, Flatpak progress, Snap changes, Nix realisation,

View file

@ -3,6 +3,23 @@
Rolling note between work sessions. **Update this file before you finish**, then Rolling note between work sessions. **Update this file before you finish**, then
commit it. It should be short and current; use `git log` for detail. commit it. It should be short and current; use `git log` for detail.
- **Nix executable integration (2026-10-01):** `sys install --nix` now uses a
persistent `/nix/var/nix/profiles/profile`; `nix prepare` still only
realises packages. New Nix bootstrap writes `/etc/profile.d/nix.sh` with
client, shared and per-user XDG profile bins on PATH; the Mango session
sources it before launching the compositor and imports PATH into systemd's
user manager. Install verification checks the active profile and reports
real executable names. `cmatrix` was installed through the new reviewed
`sys` action on a disposable encrypted VM overlay; the binary and PATH
worked, and `sys list --nix` reported its manifest. The existing visible
playground received the new static `sys`, profile script and session
launcher, then passed an authenticated 9/9 serial boot check; its QEMU
window was relaunched in windowed mode. Rust format, Clippy, workspace
tests, release and static builds pass. `make doctor` still reports only
the host-space gate (11 GiB free versus 20 GiB for a new VM); the test used
an existing qcow2 backing image and a temporary COW overlay. A fresh
ISO/install remains unverified.
- **Package-lane terminal and reliability pass (2026-10-01):** Human `sys` - **Package-lane terminal and reliability pass (2026-10-01):** Human `sys`
sessions now stream Portage compilation, Flatpak transaction progress, sessions now stream Portage compilation, Flatpak transaction progress,
Snap operations, Nix realisation, custom ebuild builds and AppImage download Snap operations, Nix realisation, custom ebuild builds and AppImage download

View file

@ -153,6 +153,7 @@ disposable VM; `serial-driver.py recovery` now automates the same check.
| Package information (`sys info`, `--legacy`) | yes | yes (installed/available, version/deps/size/provenance; ambiguity flagged) | yes (VM read-only group) | no | | Package information (`sys info`, `--legacy`) | yes | yes (installed/available, version/deps/size/provenance; ambiguity flagged) | yes (VM read-only group) | no |
| Cross-source update check/apply (`sys updates`, `apply updates`) | yes | yes (exact per-source transactions with full Flatpak commits/snap revisions, pinned and revalidated; manual/project-specific refused; unchecked and failed lanes never claim freshness) | 2026-10-01 six-lane `sys updates` matrix PASS=75 and manual AppImage/Nix/custom-ebuild honesty checks; earlier Flatpak reviewed pinned update and Portage update VM-verified; direct Snap refresh completed with no newer revision, exact Snap apply-updates transaction unit-tested only | no | | Cross-source update check/apply (`sys updates`, `apply updates`) | yes | yes (exact per-source transactions with full Flatpak commits/snap revisions, pinned and revalidated; manual/project-specific refused; unchecked and failed lanes never claim freshness) | 2026-10-01 six-lane `sys updates` matrix PASS=75 and manual AppImage/Nix/custom-ebuild honesty checks; earlier Flatpak reviewed pinned update and Portage update VM-verified; direct Snap refresh completed with no newer revision, exact Snap apply-updates transaction unit-tested only | no |
| Nix active-profile inventory (`sys list --nix`) | yes | yes (manifest v1/v2/v3; scope; generations vs store) | yes (NIX_ENABLED=yes install: real `nodejs-slim` profile listed and filtered; a re-run correctly reported a dangling profile. **2026-09-26 on the fresh unpinned install**: bootstrap present (`/nix/store` populated, `default` link valid, `nix 2.24.9` runs); `sys list --nix` truthfully reports the base system profile has no package manifest. GC-dangling repro: `nix-collect-garbage` is not on root's PATH; user-level install/GC repro attempted — see VM evidence. **2026-09-28 run 15**: modern XDG per-user profiles enumerated — `nix profile install nixpkgs#hello` as `phoebus` into `~/.local/state/nix/profiles/profile`, `sys list --nix` reports `hello 2.12.3 [per-user:phoebus]` with 824 store paths noted separately; installer now normalizes `/nix` + `/etc/nix*` permissions so unprivileged clients work) | no | | Nix active-profile inventory (`sys list --nix`) | yes | yes (manifest v1/v2/v3; scope; generations vs store) | yes (NIX_ENABLED=yes install: real `nodejs-slim` profile listed and filtered; a re-run correctly reported a dangling profile. **2026-09-26 on the fresh unpinned install**: bootstrap present (`/nix/store` populated, `default` link valid, `nix 2.24.9` runs); `sys list --nix` truthfully reports the base system profile has no package manifest. GC-dangling repro: `nix-collect-garbage` is not on root's PATH; user-level install/GC repro attempted — see VM evidence. **2026-09-28 run 15**: modern XDG per-user profiles enumerated — `nix profile install nixpkgs#hello` as `phoebus` into `~/.local/state/nix/profiles/profile`, `sys list --nix` reports `hello 2.12.3 [per-user:phoebus]` with 824 store paths noted separately; installer now normalizes `/nix` + `/etc/nix*` permissions so unprivileged clients work) | no |
| Nix executable integration (`sys install --nix`, user profile PATH) | yes | yes (profile command, PATH script, manifest and executable verification) | yes (2026-10-01 disposable encrypted overlay: real `cmatrix` installed into shared profile, directly executable, on shell PATH and listed; visible playground updated and 9/9 serial boot checks passed; graphical session PATH inheritance is unit-tested but not yet VM-inspected) | no |
| Catalogue maintenance (`depclean`, `clean cache`, `owners`, `deps`/`rdeps`) | yes | yes (structured depclean effects; cache-cleanup dry-run review + failure propagation; VDB dependency metadata) | yes (VM: depclean + cache-cleanup journeys; deps read-only) | no | | Catalogue maintenance (`depclean`, `clean cache`, `owners`, `deps`/`rdeps`) | yes | yes (structured depclean effects; cache-cleanup dry-run review + failure propagation; VDB dependency metadata) | yes (VM: depclean + cache-cleanup journeys; deps read-only) | no |
| AI-default catalogue routing (source flags constrain, never bypass) | yes | yes (investigation loop, full backend classification + optional-backend rewrite, fallback offers exact `--legacy` command) | yes (read-only routing cases) | no | | AI-default catalogue routing (source flags constrain, never bypass) | yes | yes (investigation loop, full backend classification + optional-backend rewrite, fallback offers exact `--legacy` command) | yes (read-only routing cases) | no |
| Alternate-root catalogue/update/maintenance rooting | yes | yes (chroot for Portage/Flatpak/Nix; Snap refused; recording-runner no-host-command tests) | yes (VM: alternate-root Snap refused) | no | | Alternate-root catalogue/update/maintenance rooting | yes | yes (chroot for Portage/Flatpak/Nix; Snap refused; recording-runner no-host-command tests) | yes (VM: alternate-root Snap refused) | no |

View file

@ -204,6 +204,13 @@ installs anything and never fabricates a candidate.
| Phrase | Typed action | Kind | | Phrase | Typed action | Kind |
| --- | --- | --- | | --- | --- | --- |
| `nix prepare nodejs python312` | `nix_prepare` | mutate | | `nix prepare nodejs python312` | `nix_prepare` | mutate |
| `nix install cmatrix` | `nix_install` | mutate |
`sys install cmatrix --legacy --nix` installs into the shared Phoebus Nix
profile; its commands are on the graphical session's `PATH`. The Nix client's
default profile remains separate. Direct `nix profile install nixpkgs#cmatrix`
as a normal user uses the user's own profile, which is also on `PATH`.
`nix prepare` only realises packages for temporary `nix shell` use.
### Snap (`app-containers/snapd` through Portage) ### Snap (`app-containers/snapd` through Portage)
@ -402,11 +409,11 @@ recorded.
| `undo status` | `rollback_status` | read | | `undo status` | `rollback_status` | read |
| `history` | `history` | read | | `history` | `history` | read |
Portage, Flatpak, Snap, managed AppImage and custom ebuild package changes take Portage, Flatpak, Snap, Nix profile, managed AppImage and custom ebuild package changes take
a protective coordinated root/var snapshot before mutation. `sys undo` a protective coordinated root/var snapshot before mutation. `sys undo`
restores a chosen snapshot on the next boot; `/home` remains outside that restores a chosen snapshot on the next boot; `/home` remains outside that
snapshot. Nix `prepare` only realises a development attribute and does not snapshot. Nix `prepare` only realises a development attribute and does not
install it into a persistent profile. User-managed Nix profile changes and install it into a persistent profile. Direct user-managed Nix profile changes and
snapd's automatic background refreshes are outside a `sys` transaction. snapd's automatic background refreshes are outside a `sys` transaction.
## Desktop assistant bridge (`sys --assistant-bridge`) ## Desktop assistant bridge (`sys --assistant-bridge`)

View file

@ -79,6 +79,10 @@ pub enum SystemAction {
NixPrepare { NixPrepare {
packages: Vec<String>, packages: Vec<String>,
}, },
/// Install bounded nixpkgs packages into the shared Phoebus profile.
NixInstall {
packages: Vec<String>,
},
CreateSnapshot { CreateSnapshot {
operation: String, operation: String,
}, },
@ -366,6 +370,9 @@ impl SystemAction {
SystemAction::NixPrepare { packages } => { SystemAction::NixPrepare { packages } => {
format!("realise Nix development packages: {}", packages.join(", ")) format!("realise Nix development packages: {}", packages.join(", "))
} }
SystemAction::NixInstall { packages } => {
format!("install Nix packages: {}", packages.join(", "))
}
SystemAction::CreateSnapshot { operation } => { SystemAction::CreateSnapshot { operation } => {
format!("create a Btrfs snapshot before: {operation}") format!("create a Btrfs snapshot before: {operation}")
} }
@ -576,6 +583,7 @@ impl SystemAction {
| SystemAction::RemovePackage { .. } | SystemAction::RemovePackage { .. }
| SystemAction::FlatpakInstall { .. } | SystemAction::FlatpakInstall { .. }
| SystemAction::FlatpakRemove { .. } | SystemAction::FlatpakRemove { .. }
| SystemAction::NixInstall { .. }
| SystemAction::SnapInstall { .. } | SystemAction::SnapInstall { .. }
| SystemAction::SnapRemove { .. } | SystemAction::SnapRemove { .. }
| SystemAction::SnapRefresh { .. } | SystemAction::SnapRefresh { .. }
@ -670,7 +678,7 @@ impl SystemAction {
SystemAction::FlatpakInstall { .. } SystemAction::FlatpakInstall { .. }
| SystemAction::FlatpakRemove { .. } | SystemAction::FlatpakRemove { .. }
| SystemAction::FlatpakList => Some(Backend::Flatpak), | SystemAction::FlatpakList => Some(Backend::Flatpak),
SystemAction::NixPrepare { .. } => Some(Backend::Nix), SystemAction::NixPrepare { .. } | SystemAction::NixInstall { .. } => Some(Backend::Nix),
SystemAction::SnapFind { .. } SystemAction::SnapFind { .. }
| SystemAction::SnapInfo { .. } | SystemAction::SnapInfo { .. }
| SystemAction::SnapInstall { .. } | SystemAction::SnapInstall { .. }
@ -742,7 +750,7 @@ impl SystemAction {
} }
} }
SystemAction::FlatpakList => Ok(()), SystemAction::FlatpakList => Ok(()),
SystemAction::NixPrepare { packages } => { SystemAction::NixPrepare { packages } | SystemAction::NixInstall { packages } => {
if packages.is_empty() { if packages.is_empty() {
return Err("nix prepare requires at least one package".into()); return Err("nix prepare requires at least one package".into());
} }
@ -1721,7 +1729,7 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
if let Some(packages) = rest("nix install ") { if let Some(packages) = rest("nix install ") {
let packages: Vec<String> = packages.split_whitespace().map(str::to_string).collect(); let packages: Vec<String> = packages.split_whitespace().map(str::to_string).collect();
if !packages.is_empty() { if !packages.is_empty() {
return Some(SystemAction::NixPrepare { packages }); return Some(SystemAction::NixInstall { packages });
} }
} }
@ -2110,6 +2118,12 @@ mod tests {
packages: vec!["nodejs".into(), "python312".into()] packages: vec!["nodejs".into(), "python312".into()]
}) })
); );
assert_eq!(
parse_natural("nix install cmatrix"),
Some(SystemAction::NixInstall {
packages: vec!["cmatrix".into()]
})
);
assert_eq!( assert_eq!(
parse_natural("snapshot before update"), parse_natural("snapshot before update"),
Some(SystemAction::CreateSnapshot { Some(SystemAction::CreateSnapshot {

View file

@ -1367,6 +1367,12 @@ export GDK_BACKEND=wayland,x11
export ELECTRON_OZONE_PLATFORM_HINT=auto export ELECTRON_OZONE_PLATFORM_HINT=auto
export _JAVA_AWT_WM_NONREPARENTING=1 export _JAVA_AWT_WM_NONREPARENTING=1
# Include Nix profile commands in the graphical session, even when greetd
# starts this script without a login shell. All child terminals inherit PATH.
if [ -r /etc/profile.d/nix.sh ]; then
. /etc/profile.d/nix.sh
fi
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
exec dbus-run-session -- "$0" "$@" exec dbus-run-session -- "$0" "$@"
fi fi
@ -1470,7 +1476,7 @@ fi
if command -v dbus-update-activation-environment >/dev/null 2>&1; then if command -v dbus-update-activation-environment >/dev/null 2>&1; then
dbus-update-activation-environment --systemd \ dbus-update-activation-environment --systemd \
WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE XDG_RUNTIME_DIR \ WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE XDG_RUNTIME_DIR \
QT_QPA_PLATFORM >/dev/null 2>&1 || true QT_QPA_PLATFORM PATH >/dev/null 2>&1 || true
fi fi
# Exactly one shell: DMS, bound to mango-session.target. Verify it actually # Exactly one shell: DMS, bound to mango-session.target. Verify it actually

View file

@ -1739,6 +1739,10 @@ pub fn execute_inner(
let prepared = crate::nix::prepare_dev_packages(exec, root, packages)?; let prepared = crate::nix::prepare_dev_packages(exec, root, packages)?;
format!("realised Nix development packages: {}", prepared.join(", ")) format!("realised Nix development packages: {}", prepared.join(", "))
} }
SystemAction::NixInstall { packages } => {
let installed = crate::nix::install_profile_packages(exec, root, packages)?;
format!("installed into the Nix profile: {}", installed.join(", "))
}
SystemAction::UpdateSystem => { SystemAction::UpdateSystem => {
portage_world_update(exec, root)?; portage_world_update(exec, root)?;
"system update complete".to_string() "system update complete".to_string()

View file

@ -373,7 +373,7 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
if crate::nix::installed(root) { if crate::nix::installed(root) {
let mut c = Candidate::new(Backend::Nix, name, "nixpkgs (pinned)"); let mut c = Candidate::new(Backend::Nix, name, "nixpkgs (pinned)");
c.verified = true; c.verified = true;
c.update_reliability = UpdateReliability::Automatic; c.update_reliability = UpdateReliability::Manual;
c.sandbox = SandboxLevel::None; c.sandbox = SandboxLevel::None;
if !phoebus_core::action::valid_nix_attribute(name) { if !phoebus_core::action::valid_nix_attribute(name) {
c.available = false; c.available = false;
@ -384,7 +384,8 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
c.notes c.notes
.push(format!("attribute `{name}` does not exist in nixpkgs")); .push(format!("attribute `{name}` does not exist in nixpkgs"));
} else { } else {
c.notes.push("Nix provides a pinned development environment, not a permanent global installation".into()); c.notes
.push("Installs into the shared Phoebus Nix profile; commands are on PATH".into());
} }
out.push(c); out.push(c);
} }
@ -901,8 +902,10 @@ pub fn resolve_for_backend(
{ {
let mut c = Candidate::new(Backend::Nix, application, "nixpkgs (pinned)"); let mut c = Candidate::new(Backend::Nix, application, "nixpkgs (pinned)");
c.verified = true; c.verified = true;
c.update_reliability = UpdateReliability::Automatic; c.update_reliability = UpdateReliability::Manual;
c.notes.push("Nix provides a pinned development environment, not a permanent global installation".into()); c.notes.push(
"Installs into the shared Phoebus Nix profile; commands are on PATH".into(),
);
candidates.push(c); candidates.push(c);
} }
} }

View file

@ -219,7 +219,7 @@ pub fn action_for(_exec: &Exec, root: &Path, candidate: &Candidate) -> Result<Sy
channel: None, channel: None,
classic: false, classic: false,
}), }),
Backend::Nix => Ok(SystemAction::NixPrepare { Backend::Nix => Ok(SystemAction::NixInstall {
packages: vec![candidate.id.clone()], packages: vec![candidate.id.clone()],
}), }),
Backend::AppImage => Err(ExecError::operation( Backend::AppImage => Err(ExecError::operation(
@ -788,11 +788,7 @@ pub fn verify_installed(exec: &Exec, root: &Path, resolved: &ResolvedInstall) ->
crate::appimage::info(root, &c.id)?; crate::appimage::info(root, &c.id)?;
Ok(format!("verified: managed AppImage {} has a record", c.id)) Ok(format!("verified: managed AppImage {} has a record", c.id))
} }
Backend::Nix => Ok(format!( Backend::Nix => crate::nix::verify_profile_install(root, &c.id),
"the Nix packages were realised; identity is recorded in the transaction, \
and `nix shell nixpkgs#{}` is the supported way to use them",
c.id
)),
Backend::CustomEbuild => { Backend::CustomEbuild => {
if phoebus_core::action::valid_ebuild_atom(&c.id) if phoebus_core::action::valid_ebuild_atom(&c.id)
&& chooser::installed_copies(exec, root, &resolved.request.application) && chooser::installed_copies(exec, root, &resolved.request.application)
@ -825,9 +821,7 @@ fn verification_plan(candidate: &Candidate) -> String {
Backend::Flatpak => "`flatpak list` will be checked for the application id".into(), Backend::Flatpak => "`flatpak list` will be checked for the application id".into(),
Backend::Snap => "`snap list` will be checked for the snap".into(), Backend::Snap => "`snap list` will be checked for the snap".into(),
Backend::AppImage => "the managed record and file will be checked".into(), Backend::AppImage => "the managed record and file will be checked".into(),
Backend::Nix => { Backend::Nix => "the shared Nix profile and its commands will be checked".into(),
"the command will be reported; Nix identity is recorded in the transaction".into()
}
Backend::CustomEbuild => { Backend::CustomEbuild => {
"the Portage package database will be checked for the custom atom".into() "the Portage package database will be checked for the custom atom".into()
} }

View file

@ -21,6 +21,22 @@ pub const NIX_SHA256: &str = "3c0779e4878d1289cf3fbb158ec5ea9bdf61dfb9b4efac6b3b
const NIX_TARBALL_DIR: &str = "nix-2.24.9-x86_64-linux"; const NIX_TARBALL_DIR: &str = "nix-2.24.9-x86_64-linux";
pub(crate) const NIX_STORE_NAME: &str = "2nhrwv91g6ycpyxvhmvc0xs8p92wp4bk-nix-2.24.9"; pub(crate) const NIX_STORE_NAME: &str = "2nhrwv91g6ycpyxvhmvc0xs8p92wp4bk-nix-2.24.9";
const NIX_BUILD_USERS: u32 = 8; const NIX_BUILD_USERS: u32 = 8;
/// Shared profile used by `sys install --nix`. The default profile contains
/// the Nix client itself and must not be replaced by application installs.
pub const PHOEBUS_PROFILE: &str = "/nix/var/nix/profiles/profile";
pub const NIX_PROFILE_SCRIPT: &str = r#"# Nix client and packages; the user's profile takes precedence.
# Keep profile paths present before the first package is installed so newly
# installed commands become available in the current graphical session.
for _nix_bin in /nix/var/nix/profiles/default/bin /nix/var/nix/profiles/profile/bin "${XDG_STATE_HOME:-$HOME/.local/state}/nix/profiles/profile/bin"; do
case ":$PATH:" in
*":$_nix_bin:"*) ;;
*) PATH="$_nix_bin:$PATH" ;;
esac
done
export PATH
unset _nix_bin
"#;
fn nix_store_bin() -> String { fn nix_store_bin() -> String {
format!("/nix/store/{NIX_STORE_NAME}/bin/nix-store") format!("/nix/store/{NIX_STORE_NAME}/bin/nix-store")
@ -236,11 +252,7 @@ fn bootstrap(exec: &Exec, root: &Path, tarball: &Path) -> Result<()> {
&target_path(root, "root/.nix-profile"), &target_path(root, "root/.nix-profile"),
Path::new("/nix/var/nix/profiles/default"), Path::new("/nix/var/nix/profiles/default"),
)?; )?;
write_file( write_file(root, "etc/profile.d/nix.sh", NIX_PROFILE_SCRIPT)?;
root,
"etc/profile.d/nix.sh",
"export PATH=/nix/var/nix/profiles/default/bin:$PATH\n",
)?;
// The daemon units ship inside the store; symlink them and create the // The daemon units ship inside the store; symlink them and create the
// `.wants` links directly (systemctl enable can be a no-op in a chroot). // `.wants` links directly (systemctl enable can be a no-op in a chroot).
@ -697,6 +709,83 @@ pub fn prepare_dev_packages(exec: &Exec, root: &Path, packages: &[String]) -> Re
Ok(prepared) Ok(prepared)
} }
/// Install into the shared profile, which is on every Phoebus user's PATH.
/// All attributes are validated before Nix can change a profile generation.
pub fn install_profile_packages(
exec: &Exec,
root: &Path,
packages: &[String],
) -> Result<Vec<String>> {
if packages.is_empty() || packages.iter().any(|p| !valid_nix_attribute(p)) {
return Err(ExecError::operation(
"nix",
"install profile packages",
"expected one or more bounded nixpkgs attributes",
));
}
let mut args = vec![
"profile".to_string(),
"install".to_string(),
"--profile".to_string(),
PHOEBUS_PROFILE.to_string(),
];
args.extend(packages.iter().map(|p| format!("nixpkgs#{p}")));
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
crate::portage::chroot(
exec,
root,
"/nix/var/nix/profiles/default/bin/nix",
&borrowed,
)?;
Ok(packages.to_vec())
}
/// Confirm that the active shared profile contains the requested attribute.
/// Report executable names that the user can invoke directly.
pub fn verify_profile_install(root: &Path, attribute: &str) -> Result<String> {
use std::os::unix::fs::PermissionsExt;
let inventory = installed_packages(root);
let package = inventory
.packages
.iter()
.find(|p| p.profile == "profile" && (p.path == attribute || p.name == attribute))
.ok_or_else(|| {
ExecError::operation(
"nix",
"verify profile install",
format!("Nix did not report {attribute} in the active Phoebus profile"),
)
})?;
let store_bin = root
.join(package.store_path.trim_start_matches('/'))
.join("bin");
let profile_bin = root
.join(PHOEBUS_PROFILE.trim_start_matches('/'))
.join("bin");
let mut commands = Vec::new();
if let Ok(entries) = std::fs::read_dir(&store_bin) {
for entry in entries.flatten() {
let name = entry.file_name();
if std::fs::metadata(profile_bin.join(&name))
.is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
{
commands.push(name.to_string_lossy().to_string());
}
}
}
commands.sort();
if commands.is_empty() {
Ok(format!(
"verified: {attribute} is installed in the Phoebus Nix profile (no commands exposed)"
))
} else {
Ok(format!(
"verified: {attribute} is installed; run {} directly",
commands.join(", ")
))
}
}
/// A bounded nixpkgs attribute: no slashes, URLs, or flake references. /// A bounded nixpkgs attribute: no slashes, URLs, or flake references.
pub fn valid_nix_attribute(value: &str) -> bool { pub fn valid_nix_attribute(value: &str) -> bool {
phoebus_core::action::valid_nix_attribute(value) phoebus_core::action::valid_nix_attribute(value)
@ -862,6 +951,70 @@ mod tests {
assert!(!valid_nix_attribute("a b")); assert!(!valid_nix_attribute("a b"));
} }
#[test]
fn sys_nix_install_uses_a_persistent_profile() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone(), false);
let root = Path::new(&exec.root);
let names = install_profile_packages(&exec, root, &["cmatrix".into()]).unwrap();
assert_eq!(names, ["cmatrix"]);
let calls = runner.recorded();
assert_eq!(calls.len(), 1);
let args = &calls[0].args;
assert!(args.iter().any(|a| a == "profile"));
assert!(args.iter().any(|a| a == "install"));
assert!(args.iter().any(|a| a == PHOEBUS_PROFILE));
assert!(args.iter().any(|a| a == "nixpkgs#cmatrix"));
assert!(!args.iter().any(|a| a == "shell"));
assert!(install_profile_packages(&exec, root, &["bad/name".into()]).is_err());
assert_eq!(runner.recorded().len(), 1);
}
#[test]
fn profile_script_puts_user_and_shared_commands_on_path() {
let output = std::process::Command::new("sh")
.arg("-c")
.arg(format!("{NIX_PROFILE_SCRIPT}\nprintf '%s' \"$PATH\""))
.env("HOME", "/home/example")
.env("PATH", "/usr/bin:/bin")
.output()
.unwrap();
assert!(output.status.success());
let path = String::from_utf8(output.stdout).unwrap();
assert!(path.contains("/home/example/.local/state/nix/profiles/profile/bin"));
assert!(path.contains("/nix/var/nix/profiles/profile/bin"));
assert!(path.contains("/nix/var/nix/profiles/default/bin"));
}
#[test]
fn profile_install_verification_names_the_command() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let package = root.join("nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-cmatrix-2.0");
let profile = root.join("nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-profile");
std::fs::create_dir_all(package.join("bin")).unwrap();
std::fs::create_dir_all(profile.join("bin")).unwrap();
std::fs::write(package.join("bin/cmatrix"), b"fixture").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(
package.join("bin/cmatrix"),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
std::os::unix::fs::symlink(package.join("bin/cmatrix"), profile.join("bin/cmatrix"))
.unwrap();
std::fs::write(
profile.join("manifest.json"),
r#"{"version": 3, "elements": {"cmatrix": {"active": true, "attrPath": "cmatrix", "storePaths": ["/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-cmatrix-2.0"]}}}"#,
)
.unwrap();
let profiles = root.join("nix/var/nix/profiles");
std::fs::create_dir_all(&profiles).unwrap();
std::os::unix::fs::symlink(&profile, profiles.join("profile")).unwrap();
let result = verify_profile_install(root, "cmatrix").unwrap();
assert!(result.contains("run cmatrix directly"), "{result}");
}
fn profile_manifest_v3() -> &'static str { fn profile_manifest_v3() -> &'static str {
r#"{ r#"{
"version": 3, "version": 3,

View file

@ -560,7 +560,7 @@ fn apply_backend_filter(
channel: None, channel: None,
classic: false, classic: false,
}, },
Backend::Nix => SystemAction::NixPrepare { Backend::Nix => SystemAction::NixInstall {
packages: vec![atom], packages: vec![atom],
}, },
other => { other => {

View file

@ -146,13 +146,13 @@ else
report appimage-remove FAIL "$(failure "$WORK/appimage-remove.out")" report appimage-remove FAIL "$(failure "$WORK/appimage-remove.out")"
fi fi
# Nix is a developer realisation lane: `sys install --nix` must evaluate and # A reviewed Nix install must create a persistent profile executable.
# fetch the exact nixpkgs attribute, then explain how to use it with nix shell. if run_root install hello --legacy --nix >"$WORK/nix-install.out" 2>&1 && \
if run_root install hello --legacy --nix >"$WORK/nix-prepare.out" 2>&1 && \ test -x /nix/var/nix/profiles/profile/bin/hello && \
grep -q 'nix shell nixpkgs#hello' "$WORK/nix-prepare.out"; then grep -q 'run hello directly' "$WORK/nix-install.out"; then
report nix-prepare PASS 'attribute realised and usage explained' report nix-install PASS 'profile command is executable without nix shell'
else else
report nix-prepare FAIL "$(failure "$WORK/nix-prepare.out")" report nix-install FAIL "$(failure "$WORK/nix-install.out")"
fi fi
echo "===SYS-LANES-END=== SUMMARY PASS=$PASS FAIL=$FAIL" echo "===SYS-LANES-END=== SUMMARY PASS=$PASS FAIL=$FAIL"