Compare commits

..

No commits in common. "bab5f413ed36a7a6dfa5b8e70b5e08a885bf66e2" and "05d70753411bb201b83d803791a75fcdd21914bc" have entirely different histories.

16 changed files with 707 additions and 2643 deletions

View file

@ -3,72 +3,6 @@
All notable changes are recorded here. The authoritative history is `git log`; All notable changes are recorded here. The authoritative history is `git log`;
this file is the curated, human-readable summary. this file is the curated, human-readable summary.
## 2026-09-25 — Fix the `sys` catalogue review findings (host/target, revalidation, update effects, Nix inventory, dependencies)
Follow-up to the package-management interface: seven review findings are fixed,
each with regression tests, and the installed-system acceptance matrix is
extended and re-run.
- **Host/target confusion closed (finding 1).** Every catalogue, update-check,
information and maintenance query is now built for the *intended target* —
directly for `/`, or inside the target chroot for an alternate root. Snap acts
on the running daemon and is reported unavailable (and refused for mutation)
for an alternate root instead of ever touching the host. Availability checks
resolve tools from the target (`Exec::tool_in_target`), so a host Flatpak,
`eclean` or `qdepends` cannot leak into a target operation. Recording-runner
tests assert alternate-root search/update/cleanup and Snap paths issue no host
commands.
- **Maintenance revalidation (finding 2).** `resolves_effects` now covers
`Depclean`, `ApplyUpdates` and `CleanCache`, so they are re-resolved at the
privileged execution boundary and within multi-action plans. Depclean removals
are parsed into **structured `PackageEffect`s** (`emerge --pretend
--depclean`), so a changed removal set changes the digest and aborts before an
unapproved mutation; a regression test proves drift is refused with no
destructive command run.
- **Exact Flatpak/Snap update effects (finding 3).** `ApplyUpdates` resolves a
reviewable per-source plan with the affected identities and versions; each
Flatpak app is updated by ref and each snap by name, and the plan is bound to
approval and re-checked immediately before execution. Unrestricted update-all
is gone. Lanes with no safe system-level transaction (Nix/AppImage/custom
ebuild) are refused with a clear limitation. Destructive cache cleanup now
reviews each cleaner's non-destructive dry run and binds the item set to
approval (`ResolvedPlan.cleanup`), which is part of the digest.
- **Complete source constraints (finding 4).** `SystemAction::backend()`
classifies Portage-only actions (`UpdateSystem`, `RemovePackage`,
`Depclean`, `PrepareUpdates`, `InspectUpdates`, `PackageOwners`,
`PackageDependencies`); `constrain_action` rewrites optional-backend discovery
and selection (`DiscoverCandidates`, `ChoosePackage`) to the constrained lane
*before* querying, and refuses the cross-lane `InspectInstallation`. Unit tests
prove a Flatpak-constrained request cannot investigate or mutate
Portage/Snap/Nix through any action variant.
- **Cache-cleanup truthfulness (finding 5).** Portage cleaner errors are no
longer converted to text while the action returns success. A cleaner that ran
and failed fails the whole action (with partial successes preserved), an
unavailable cleaner is reported distinctly from one that found nothing, and
the report reaches the command exit status, assistant response and transaction
history.
- **Nix inventory (finding 6).** Inventory enumerates the packages of the active
Nix profiles from each profile's `manifest.json` (v1/v2/v3), retaining profile
and user scope and package identity; historical generations and realised store
paths are reported separately. Unsupported manifest formats and base profiles
are stated explicitly rather than shown as an empty inventory. Filtering finds
a package such as `nodejs` in a supported profile.
- **Dependency inspection (finding 7).** Forward and reverse dependencies now
come from the authoritative installed VDB metadata
(`DEPEND`/`RDEPEND`/`BDEPEND`, with a `qdepends` tree fallback) instead of an
`emerge --pretend` merge plan. Already-satisfied, conditional/versioned and
blocker dependencies are preserved; the requested package is never its own
dependency; a failed query is distinguished from a genuinely empty set.
- **Tests:** +28 (core/executor/installer) covering alternate-root chrooting,
structured depclean effects and digest drift, exact Flatpak identities, cache
cleanup review and failure propagation, constraint rewrite/refusal, Nix
manifest parsing, and dependency parsing/inspection. `make test` passes
(`cargo test --workspace`).
- **VM-verified (disposable installed clone):** the read-only acceptance matrix
is extended with `snap-alternate-root`, `list-nix-legacy` and `deps-legacy`,
and reports `SUMMARY PASS=37 FAIL=0`. _(Fresh-install and mutating journeys:
see `docs/HANDOFF.md` for the current verified/blocked state.)_
## 2026-09-25 — Complete the `sys` package-management interface (search/list/info/updates/maintenance) ## 2026-09-25 — Complete the `sys` package-management interface (search/list/info/updates/maintenance)
Adds a complete package catalogue on top of the typed-action architecture. AI is Adds a complete package catalogue on top of the typed-action architecture. AI is

View file

@ -3,126 +3,159 @@
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.
- **Last updated:** this session (2026-09-25). Follow-up to commit `05d7075`: - **Last updated:** this session (2026-09-25), completion of the `sys`
the seven review findings on the `sys` package-management interface are fixed package-management interface: unified cross-source search, installed-package
(host/target rooting, maintenance effect revalidation, exact Flatpak/Snap inventory, package information, consistent per-source update check/apply, and
update effects, complete source constraints, truthful cache-cleanup outcomes, maintenance (depclean/cache/owners/deps), all as validated typed actions
Nix active-profile inventory, VDB-based dependency inspection), with shared by the CLI and assistant. AI remains the default for every operation;
regression tests. The disposable-VM acceptance matrix is extended and the `--legacy` is the only user-facing opt-in to deterministic handling. A source
fresh-install / mutating / rollback journeys below were completed. flag constrains the AI workflow and never bypasses it. See
- **Interface contract (unchanged):** every ordinary request uses the AI `docs/SYS.md` "Package catalogue" and the CHANGELOG entry.
workflow; only an explicit `--legacy` selects deterministic handling; source - **Current focus:**
flags constrain the AI and never bypass it; a missing model stops the workflow 1. **New typed actions (`phoebus-core::action`):** `SearchPackages` gained an
and offers the exact `--legacy` command without executing it; both modes share optional `backend`; added `ListPackages`, `PackageInfo`, `PackageOwners`,
the same validated typed actions, approval controls and execution layer. `PackageDependencies`, `Depclean`, `CleanCache`, `CheckUpdates`,
`ApplyUpdates`. Read-only variants are non-mutating and need no root;
## What this session changed (code) `ApplyUpdates`/`Depclean` are High risk (protective snapshot), `CleanCache`
Medium.
1. **Host/target rooting (finding 1).** `Exec::tool_in_target` resolves tools 2. **Executor catalogue (`phoebus-executor::query`, `phoebus-core::catalog`):**
from the target; `actions::target_spec` is shared by catalogue, chooser and search/inventory/info across Portage, Flatpak, Snap, managed AppImages, Nix
update paths. Snap is host-only and is reported unavailable (and refused for and staged custom ebuilds. Each lane reports unavailable / failed / empty
mutation) for an alternate root. Recording-runner tests assert no host distinctly. Nix profiles are listed; store paths are reported separately as
`flatpak`/`snap` process is invoked for an alternate root. realised dependencies. Custom ebuilds are never double-counted (they appear
2. **Maintenance revalidation (finding 2).** `resolves_effects` covers under Portage). Portage VDB reading (`portage::installed_packages`) and
`Depclean`/`ApplyUpdates`/`CleanCache`; depclean removals are structured `emerge --search` parsing (`portage::parse_search`) added.
`PackageEffect`s parsed from `emerge --pretend --depclean`, so a changed 3. **Updates + maintenance:** `check_updates` filters the unified overview;
removal set changes the digest and aborts at the execution boundary (and `apply_updates` runs each lane and returns a truthful per-source report,
within multi-action plans). Plan aggregation now carries `cleanup` intents. failing the action when an attempted source fails; AppImage/Nix are
3. **Exact update effects (finding 3).** `ApplyUpdates` resolves per-source explained as manual/project-specific. `depclean` and Portage `ApplyUpdates`
effects (each Flatpak app by ref, each snap by name) bound to approval and are previewed from `emerge --pretend` at review time and bound by digest.
revalidated; unrestricted update-all is gone. Lanes with no safe transaction 4. **AI-default routing (`phoebus-ai::assistant::run_assistant`):** the general
are refused. Cache cleanup reviews each cleaner's dry run via assistant now runs a bounded read-only investigation loop
`ResolvedPlan.cleanup`. (`kind:"investigate"` / `kind:"plan"`, `parse_step`, `is_general_investigation_action`)
4. **Source constraints (finding 4).** `backend()` classifies Portage-only before answering. `service::plan_general` supplies the read-only executor,
actions; `constrain_action` rewrites `DiscoverCandidates`/`ChoosePackage` and applies the source constraint to investigation requests and the final plan
refuses the cross-lane `InspectInstallation` before querying. (`constrain_action`: rewrite lane-selectable queries, refuse a foreign
5. **Cache-cleanup truthfulness (finding 5).** A cleaner that ran and failed lane), and accepts an empty action list as a pure answer. `sys` renders an
fails the action (partial successes preserved); unavailable is distinct; answer without executing; a missing model prints the exact `--legacy`
the report reaches exit status, assistant response and transaction history. command.
6. **Nix inventory (finding 6).** Active-profile `manifest.json` (v1/v2/v3) - **Last verified (this session):**
packages are enumerated with profile/user scope and identity; historical - `cargo fmt --all -- --check` clean; `cargo clippy --workspace --all-targets`
generations and realised store paths are separate; unsupported formats and exits 0 (only pre-existing lints remain).
base profiles are stated explicitly. - `cargo test --workspace`: 645 passed, 0 failed (was 602). New coverage
7. **Dependencies (finding 7).** Forward/reverse dependencies use installed VDB includes: catalogue action classification/validation and natural phrases;
`DEPEND`/`RDEPEND`/`BDEPEND` (`qdepends` tree fallback), include catalogue report rendering (unavailable/failed/empty, installed/scope);
already-satisfied/conditional/versioned deps, never self, and distinguish a per-lane search/inventory/info with a recording runner; VDB metadata and
failed query from an empty set. no-double-count; ambiguity; depclean preview/skip; per-source update
failure; forward dependencies; AI step parsing, the general investigation
Unit tests: `cargo test --workspace` (all green; see CHANGELOG). Build/static loop, mutating-investigation refusal; `plan_general` investigation/answer,
binaries: `make build` and `make static`; the static `sys` built from the final foreign-lane refusal and constraint rewrite; and CLI routing: search/list/
tree has SHA-256 `22232a25…` (see the VM log `SYS_SHA`). info/updates without `--legacy` enter the AI workflow and never run
deterministically, a source flag constrains and never bypasses, `--legacy`
## Verified in disposable VMs (this session) never contacts a model, read-only catalogue commands need no root and write
no transaction.
- **Fresh install** (`fresh-install-1.qcow2`, test.conf `DESKTOP_PROFILE=none`, - Host smoke test of `sys search/list/info/updates --legacy` against the live
`NIX_ENABLED=no`): `===INSTALL-RC=0===`, `NO_SECRET_LEAK`, then a detached host (real Flatpak inventory and update list rendered).
boot: `boot-systemd-running` PASS. - **Disposable-VM read-only acceptance** (`serial-driver.py boot` on a qcow2
- **Out-of-box Portage permissions:** `/etc/portage` 755, clone of the installed disk, `SYS_BIN=/tmp/sys`): `sys-acceptance.sh`
`repos.conf` 755, `repos.conf/gentoo.conf` 644, reports `SUMMARY PASS=34 FAIL=0`, including `search-legacy`, `list-legacy`,
`package.use/phoebus` 644 → non-root `sys search firefox --legacy` returns 3 `info-legacy`, `updates-legacy`, `search-no-model-offer`,
real results and `sys updates --legacy` reports 10 available. This is the `search-flag-constraint`, and the non-root maintenance refusals. Found and
fresh-install proof that `normalize_config_permissions` works without manual fixed a real defect: the installed system left `/etc/portage/repos.conf` and
repair. `/etc/portage/package.use/phoebus` root-only, so `emerge --search` failed for
- **Acceptance matrix:** `installer/tests/vm/sys-acceptance.sh` `SUMMARY PASS=37 a normal account. `portage::normalize_config_permissions` (unit-tested,
FAIL=0` on both an existing installed clone and the fresh install, including keyring excluded) makes the non-secret Portage config world-readable and
the new regressions `snap-alternate-root`, `list-nix-legacy`, `deps-legacy`. runs at config write and at finalize; with the same permissions applied to
- **Privileged mutating journeys** on the fresh install (via root; see blocked the clone, `search-legacy` returns real results (3) and `updates-legacy`
note): install + VDB, remove, history, depclean, cache cleanup (honest reports 10 available. The fresh-install re-run is pending (base install is
nonzero failure with no cleaner), alternate-root Snap refusal, and a Portage ~2 h).
`apply updates` journey — 7/7 PASS. - **Not yet verified (BLOCKED):**
- **Rollback acceptance** on a disposable clone: snapshot → controlled change - **A fresh VM install with the permission fix** (so the catalogue works
(root marker + `app-misc/hello`) → `sys undo` → detached boot. The package out of the box) has not been re-run; the base install is ~2 h. The fix is
database fingerprint returned to the pre-change value, the root marker is unit-tested and its effect was demonstrated on the disposable clone.
absent, the `/home` marker survives, and systemd is running. - **Mutating catalogue journeys** (`apply updates`, `depclean`, `clean cache`)
- **Revision:** the installed `sys` on the fresh disk matches the static build are not exercised in a VM; they need a disposable installed disk and, for
(`SYS_SHA:22232a25…`). `apply updates`, network.
- The privileged `sys --broker --execute-plan` path and replay rejection remain
## Blocked / not yet verified unit-tested only: the serial console has no root access and no Polkit agent
(`sudo -n` denied), so `pkexec` elevation cannot complete. A
- **pkexec/Polkit `sys --broker --execute-plan` path:** the serial console has no graphical/seat-providing VM or a passwordless-sudo test image is required.
Polkit agent, so `pkexec` elevation cannot complete. Privileged execution was - No AI provider credential is present; do not invent one. The general
exercised by running the same reviewed plan as root (initiator uid 0); the investigation loop is fixture-verified (scripted transport), not live.
ledger/replacement/replay logic remains unit-tested and was previously - The pre-existing `test-disk.qcow2` still cannot be unlocked (unknown
reviewed. To unblock: a seat-providing/graphical VM with a working Polkit passphrase); do not guess or brute-force.
agent, or a disposable test image with a passwordless-sudo polkit agent. - A real privileged `chown` could not be exercised on this unprivileged host;
- **Nix profile journey:** the disposable install sets `NIX_ENABLED=no`, so no verified through the injectable fixer seam and the cross-uid refusal test.
Nix profile exists in the VM. The manifest parser (v1/v2/v3, unsupported - **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
formats, inactive elements, historical generations) is unit-tested with (remote `origin`, SSH port 2222).
realistic fixtures. To unblock: install with Nix enabled and a known profile.
- **Snap install/refresh/remove:** no snapd/AppArmor in the minimal image; the
lane journey would need `app-containers/snapd`, AppArmor and network.
- **Managed AppImage acquire/launch/remove** and **custom-ebuild
stage/build/install/remove:** not run in the VM (no AppImage fixture/FUSE and
no build budget); the code paths are unit-tested.
- **Live AI:** no provider credential is present. `sys ask`/guided install and
source-constrained live AI remain unverified; do not invent a credential.
- **NVIDIA:** no GPU.
## Known blockers / risks
- A full VM install takes ~2 h; the fresh `fresh-install-1.qcow2` is now
available for future work. `make doctor` reports low host disk space; delete
build/VMs deliberately, never a physical disk.
- The pre-existing `test-disk.qcow2` still cannot be unlocked (unknown
passphrase); do not guess or brute-force.
- OpenCode transport concatenates messages; multi-turn AI investigation is
best-effort there.
## Next actions (in order) ## Next actions (in order)
1. **pkexec/Polkit broker acceptance** in a seat-providing or passwordless-agent 1. **Installed-VM read-only acceptance of the catalogue** on the booted disk:
disposable VM: successful approval, cancelled authentication, plan ```sh
replacement during authentication, replay after deleting user-owned plan # serve the static sys first:
state, and real ownership of personal settings. cp installer-rs/target/x86_64-unknown-linux-gnu/release/sys /home/dominic/vmlab/serve/
2. **Nix profile journey** with `NIX_ENABLED=yes` and a profile containing a env DISK=/var/tmp/phoebus-vm/disks/<clone>.qcow2 \
known package (`nodejs`), verifying inventory, filtering and generations. OVMF_CODE=/usr/share/OVMF/OVMF_CODE_4M.fd \
3. **Snap/AppImage/custom-ebuild lane journeys** with benign fixtures and OVMF_VARS=/var/tmp/phoebus-vm/OVMF_VARS.fd \
recorded confinement limitations. BOOT_CHECKS='... curl .../sys ...; SYS_BIN=/tmp/sys bash .../sys-acceptance.sh ...' \
4. **Live AI** (`sys ask`, source-constrained discovery, reviewed install, python3 installer/tests/vm/serial-driver.py boot
missing-model/provider-failure) once a credential or local model exists. ```
Expect `SUMMARY PASS=34 FAIL=0` (non-root), including the `search-legacy`,
`list-legacy`, `info-legacy`, `updates-legacy`, `search-no-model-offer`,
`search-flag-constraint` and non-root maintenance cases. Already run this
session on a clone of `verify-disk2.qcow2` (34/34).
2. **Privileged `--broker` acceptance in a seat-providing VM.** The remaining
unverified path is the actual `pkexec` elevation into
`sys --broker --execute-plan` (replacement during authentication, replay
after deleting user plan state, cancellation, a real privileged `chown`). It
needs a graphical Polkit agent or a passwordless-sudo disposable test image.
3. **AI-selected install journey (needs an authorised provider)**: boot the
installed disk, serve the built `sys` and a 0600 key file, then:
```sh
sudo sys --ai-provider deepseek --ai-api-key-file /run/phoebus/ai.key \
install <application>
# and the no-model control in the same run:
PHOEBUS_AI_PROVIDER= sudo sys install <application>
```
Confirm the model requests evidence, the resolver confirms the candidate,
the plan is presented before approval, and the transaction is recorded. No
credential is available here; do not invent one.
4. **Rollback VM acceptance** (`serial-driver.py rollback`) on a cloned
disposable image of the installed system.
5. **NVIDIA hardware acceptance (BLOCKED)**: needs an NVIDIA GPU.
6. **Interactive graphical user session** login into Mango / DankMaterialShell
under a physical seat or nested Wayland compositor.
## Known blockers / risks
- **A full VM install still takes hours** (base stage ~116 min). Use the already
installed disposable disk (clone it) for `sys install` journeys rather than a
fresh install.
- **No NVIDIA GPU** (and no authorised passthrough).
- **Snap needs network and AppArmor** for meaningful confinement; the lane
detects confinement honestly.
- **AppImage provides no sandbox**; do not describe it as one.
- **Custom ebuilds remain separately reviewed, untrusted artifacts**; the
install workflow never builds one during investigation.
- **OpenCode transport** concatenates messages, so multi-turn investigation is
best-effort there; the direct providers carry the full conversation.
- Harness artifacts live under `/var/tmp/phoebus-vm/` (outside git).
## Environment notes
- Dev host: Ubuntu 26.04. QEMU/OVMF/xorriso/rustfmt/clippy/ImageMagick/visudo
present. `flatpak` and `snap` clients are present on the host (not proof of
the VM lanes).
- VM harnesses: `installer/tests/vm/{gui-driver,serial-driver,appliance-driver,live-driver}.py`
and `sys-acceptance.sh`. `DISK` must be a disposable qcow2; never `/dev/*`.
- Serve fixtures from `/home/dominic/vmlab/serve` with
`python3 -m http.server 8000 --bind 127.0.0.1` (reachable as `10.0.2.2:8000`).
- The static binaries for the VM: `make static` builds `phoebus-installer` and
`sys` under `installer-rs/target/x86_64-unknown-linux-gnu/release/`.
## Definition of a good stopping point ## Definition of a good stopping point
- `make test` passes; `docs/STATUS.md`, `docs/CHANGELOG.md` and this file - `make test` passes; `docs/STATUS.md` and `docs/CHANGELOG.md` updated;
updated; committed (`scripts/agent-commit.sh`) and pushed `docs/HANDOFF.md` updated; committed (via `scripts/agent-commit.sh`) and
(`scripts/publish.sh`). pushed (`scripts/publish.sh`).

View file

@ -93,11 +93,9 @@ still not VM-verified.
| Personal preferences + alert state (user-owned, system-default precedence) | yes | yes (save/reload/isolation/precedence/failure) | yes (installed VM: saved to user config, exit 0) | no | | Personal preferences + alert state (user-owned, system-default precedence) | yes | yes (save/reload/isolation/precedence/failure) | yes (installed VM: saved to user config, exit 0) | no |
| Personal write ownership (elevated chown, symlink refusal, cross-uid refusal) | yes | yes (ownership-fixer seam + CLI refusal) | no | no | | Personal write ownership (elevated chown, symlink refusal, cross-uid refusal) | yes | yes (ownership-fixer seam + CLI refusal) | no | no |
| Personal preference does not need the root-owned system transaction log | yes | yes (CLI regression: read-only transaction dir) | yes (installed VM acceptance) | n/a | | Personal preference does not need the root-owned system transaction log | yes | yes (CLI regression: read-only transaction dir) | yes (installed VM acceptance) | n/a |
| Installed `sys` acceptance matrix (read-only/failure) | yes | yes | yes (installed VM: `PASS=37 FAIL=0`, catalogue + regression group) | no | | Installed `sys` acceptance matrix (read-only/failure) | yes | yes | yes (installed VM: `PASS=34 FAIL=0`, catalogue group included) | no |
| Portage config readable for non-root queries (`normalize_config_permissions`) | yes | yes (modes + keyring exclusion) | yes (fresh VM install: 0755/0644 out of the box; non-root `search` returns 3 results, `updates` reports 10) | no | | Portage config readable for non-root queries (`normalize_config_permissions`) | yes | yes (modes + keyring exclusion) | yes (disposable VM: search returns real results after normalisation; fresh-install re-run pending) | no |
| Privileged catalogue mutations (install/remove/depclean/cache/apply updates, alternate-root) | yes | yes (unit) | yes (fresh installed VM via root: 7/7 PASS) | no | | Privileged `--broker` plan execution + replay rejection in a VM | yes | yes (privileged entry point) | no (needs root/Polkit agent; unit-tested only) | n/a |
| Rollback acceptance (snapshot -> change -> `sys undo` -> detached verify) | yes | yes | yes (clone: package DB restored, root marker gone, `/home` survives, boot running) | no |
| Privileged `--broker` plan execution + replay rejection in a VM (pkexec path) | yes | yes (privileged entry point) | no (serial console has no Polkit agent; direct privileged execution exercised via root) | n/a |
| Transaction log (outcomes, protective snapshots) | yes | yes | read-only in installed VM; write path needs root | no | | Transaction log (outcomes, protective snapshots) | yes | yes | read-only in installed VM; write path needs root | no |
| Flatpak/Nix bounded typed actions | yes | yes | no | no | | Flatpak/Nix bounded typed actions | yes | yes | no | no |
| Shared hardware-aware source selection (all lanes) | yes | yes | no | no | | Shared hardware-aware source selection (all lanes) | yes | yes | no | no |
@ -116,12 +114,11 @@ still not VM-verified.
| `sys` validation at the execution boundary | yes | yes | no | n/a | | `sys` validation at the execution boundary | yes | yes | no | n/a |
| `sys ask` truthful failure (nonzero, stop, record) | yes | yes | no | n/a | | `sys ask` truthful failure (nonzero, stop, record) | yes | yes | no | n/a |
| Unified package search (`sys search`, all lanes, `--legacy`) | yes | yes (cross-lane; unavailable/failed/empty distinguished; source filter) | no | no | | Unified package search (`sys search`, all lanes, `--legacy`) | yes | yes (cross-lane; unavailable/failed/empty distinguished; source filter) | no | no |
| Installed-package inventory (`sys list`, all lanes, `--legacy`) | yes | yes (VDB/Flatpak/Snap/AppImage; **Nix active-profile packages** vs generations/store; custom ebuild never double-counted) | yes (VM read-only group) | no | | Installed-package inventory (`sys list`, all lanes, `--legacy`) | yes | yes (VDB/Flatpak/Snap/AppImage; Nix profiles vs store; custom ebuild never double-counted) | no | no |
| 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) | no | no |
| Cross-source update check/apply (`sys updates`, `apply updates`) | yes | yes (exact per-source identities bound to approval + revalidated; manual/project-specific refused) | yes (VM: check read-only; Portage apply journey) | no | | Cross-source update check/apply (`sys updates`, `apply updates`) | yes | yes (per-source outcomes; manual/project-specific explained) | no | 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 (Portage/Nix; unsupported reported explicitly) | no | 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, constraint rewrite/refusal, fallback offers exact `--legacy` command) | no | 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 |
| Service start/stop/restart + flatpak/nix/snapshot commands | yes | yes | no | no | | Service start/stop/restart + flatpak/nix/snapshot commands | yes | yes | no | no |
| Desktop session helpers (DMS bar/launcher/lock/idle) | yes | yes | functional test (stubs) | no | | Desktop session helpers (DMS bar/launcher/lock/idle) | yes | yes | functional test (stubs) | no |
| Mango + DankMaterialShell profile | yes | yes | live VM yes; installed desktop_install yes (174 pkgs) | no | | Mango + DankMaterialShell profile | yes | yes | live VM yes; installed desktop_install yes (174 pkgs) | no |

View file

@ -290,40 +290,27 @@ sys rdeps vim --legacy # reverse dependencies (equery)
custom ebuilds. Entries show source, identity, version, description and custom ebuilds. Entries show source, identity, version, description and
installed status where the backend provides them. installed status where the backend provides them.
- **Inventory** covers the Portage VDB, `flatpak list`, `snap list`, - **Inventory** covers the Portage VDB, `flatpak list`, `snap list`,
Phoebus-managed AppImages and the **packages of the active Nix profiles** Phoebus-managed AppImages and **Nix profiles**. Nix store paths are reported
(parsed from each profile's `manifest.json`; historical generations and separately as realised dependencies, never as installed programs. Custom
realised store paths are reported separately, never as installed programs). ebuilds install through Portage and are listed once, under Portage.
Custom ebuilds install through Portage and are listed once, under Portage.
- **Information** combines installed copies (VDB metadata: version, size, - **Information** combines installed copies (VDB metadata: version, size,
repository, `DEPEND`/`RDEPEND`/`BDEPEND`) with resolved candidates and policy repository, `RDEPEND`) with resolved candidates and policy metadata. When more
metadata. When more than one real package matches, the report is marked than one real package matches, the report is marked **ambiguous** and lists
**ambiguous** and lists every match instead of guessing. every match instead of guessing.
- **Updates** check every supported lane. Applying updates resolves the exact - **Updates** check every supported lane. Applying updates reports a truthful
affected identities per source immediately before execution (each Flatpak app per-source outcome; AppImage (pinned URL+SHA) and Nix (project/declarative)
by ref, each snap by name) and re-checks the reviewed effect set at the are explained as manual/project-specific and are never reported as updated. A
execution boundary; a changed set aborts as a stale plan. AppImage (pinned source that was attempted and failed fails the whole action while the report
URL+SHA) and Nix (project/declarative) are refused as a system-level still shows the sources that succeeded. Background **preparation**
transaction rather than reported as updated. A source that was attempted and (`prepare updates`, `what are you compiling`) remains distinct from
failed fails the whole action while the report still shows the sources that **activation**.
succeeded. Background **preparation** (`prepare updates`, `what are you - **Maintenance**: `depclean` previews its removal set with
compiling`) remains distinct from **activation**. `emerge --pretend --depclean` at review time and refuses when nothing is
- **Maintenance**: `depclean` records its removal set as **structured package selected; it preserves config files and user data. `clean cache` uses
effects** (not only prose) from `emerge --pretend --depclean` at review time, `eclean-dist`/`eclean-pkg` (Portage) or `nix-store --gc` (Nix) and never
so a changed removal set is caught before execution; it refuses when the removes an installed package. `package_owners` and `package_dependencies`
selection cannot be established, and preserves config files and user data. require `app-portage/portage-utils`/`gentoolkit` and report an explicit
`clean cache` reviews each cleaner's non-destructive dry run and binds it to unsupported error when the tool is absent.
approval; a cleaner that ran and failed propagates as a failed action while
partial successes are preserved, and an unavailable cleaner is reported
distinctly from one that found nothing. `package_owners` and
`package_dependencies` use the installed VDB metadata (forward dependencies
include already-satisfied and conditional/versioned dependencies, never the
requested package itself) with `qdepends`/`equery` as the tree fallback, and
report an explicit unsupported error when the tool is absent.
- **Rooting**: every catalogue, update-check and maintenance command is built
for the *intended target* — directly for `/`, or inside the target chroot for
an alternate root. Snap acts on the running daemon and is therefore reported
unavailable (and refused for mutation) for an alternate root rather than ever
touching the host.
- `sys inspect <service> --legacy` is unchanged: `inspect` always means service - `sys inspect <service> --legacy` is unchanged: `inspect` always means service
inspection (use `info` for packages). inspection (use `info` for packages).

View file

@ -600,19 +600,9 @@ impl SystemAction {
| SystemAction::DiscoverCandidates { backend, .. } => *backend, | SystemAction::DiscoverCandidates { backend, .. } => *backend,
SystemAction::InspectCandidate { backend, .. } => Some(*backend), SystemAction::InspectCandidate { backend, .. } => Some(*backend),
SystemAction::CheckBackend { backend } => Some(*backend), SystemAction::CheckBackend { backend } => Some(*backend),
// Portage-only actions. These must be classified so a request SystemAction::InstallPackage { .. } | SystemAction::InspectPackage { .. } => {
// constrained to another lane can never reach them through the Some(Backend::PortageSource)
// `backend() == None` loophole (UpdateSystem, RemovePackage, }
// Depclean, PrepareUpdates, ownership and dependency inspection).
SystemAction::InstallPackage { .. }
| SystemAction::InspectPackage { .. }
| SystemAction::RemovePackage { .. }
| SystemAction::UpdateSystem
| SystemAction::PrepareUpdates
| SystemAction::InspectUpdates
| SystemAction::PackageOwners { .. }
| SystemAction::PackageDependencies { .. }
| SystemAction::Depclean => Some(Backend::PortageSource),
SystemAction::FlatpakInstall { .. } SystemAction::FlatpakInstall { .. }
| SystemAction::FlatpakRemove { .. } | SystemAction::FlatpakRemove { .. }
| SystemAction::FlatpakList => Some(Backend::Flatpak), | SystemAction::FlatpakList => Some(Backend::Flatpak),

View file

@ -47,29 +47,11 @@ pub struct PackageEffect {
pub source: EffectSource, pub source: EffectSource,
} }
/// One destructive cache-cleanup intent, bound to approval.
///
/// A cleaner is only ever run after its exact dry-run item list has been
/// reviewed. `unavailable` distinguishes a missing tool from a tool that ran
/// and reported nothing to remove, so an unavailable cleaner is never presented
/// as a completed cleanup.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CleanupEffect {
/// The cleaner (e.g. `eclean-dist`, `eclean-pkg`, `nix-store --gc`).
pub cleaner: String,
/// The exact items/paths the non-destructive dry run reported.
pub items: Vec<String>,
/// The tool is not present in the target.
pub unavailable: bool,
}
/// A fully resolved, human-reviewable plan. /// A fully resolved, human-reviewable plan.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)] #[serde(default)]
pub struct ResolvedPlan { pub struct ResolvedPlan {
pub effects: Vec<PackageEffect>, pub effects: Vec<PackageEffect>,
/// Destructive cache-cleanup intents, each bound to its reviewed dry run.
pub cleanup: Vec<CleanupEffect>,
pub download_bytes: Option<u64>, pub download_bytes: Option<u64>,
/// A recovery point that will exist before the change (snapshot id). /// A recovery point that will exist before the change (snapshot id).
pub recovery_point: Option<String>, pub recovery_point: Option<String>,
@ -144,20 +126,6 @@ impl ResolvedPlan {
} }
hasher.update(b"\n"); hasher.update(b"\n");
} }
// Cleanup intents are part of the approved material change: a cleaner
// that would now delete a different item set must invalidate approval.
for cleanup in &self.cleanup {
hasher.update(b"cleanup\0");
hasher.update(cleanup.cleaner.as_bytes());
hasher.update(b"\0");
hasher.update([cleanup.unavailable as u8]);
hasher.update(b"\0");
for item in &cleanup.items {
hasher.update(item.as_bytes());
hasher.update(b"\n");
}
hasher.update(b"\0");
}
self.digest = format!("{:x}", hasher.finalize()); self.digest = format!("{:x}", hasher.finalize());
} }
@ -197,23 +165,6 @@ impl ResolvedPlan {
self.source_builds(), self.source_builds(),
self.binary_packages() self.binary_packages()
)); ));
for cleanup in &self.cleanup {
if cleanup.unavailable {
out.push_str(&format!(
" [cleanup] {} is not available in the target\n",
cleanup.cleaner
));
} else {
out.push_str(&format!(
" [cleanup] {} would remove {} item(s)\n",
cleanup.cleaner,
cleanup.items.len()
));
for item in &cleanup.items {
out.push_str(&format!(" - {item}\n"));
}
}
}
if let Some(bytes) = self.download_bytes { if let Some(bytes) = self.download_bytes {
out.push_str(&format!(" download: {} MiB\n", bytes / (1024 * 1024))); out.push_str(&format!(" download: {} MiB\n", bytes / (1024 * 1024)));
} }
@ -542,29 +493,6 @@ Total: 5 packages (2 upgrades, 2 new, 1 uninstall), Size of downloads: 10,240 Ki
assert!(!real.effects.is_empty()); assert!(!real.effects.is_empty());
} }
#[test]
fn cleanup_intents_are_part_of_the_digest_and_material_change() {
let mut a = ResolvedPlan::default();
a.cleanup.push(CleanupEffect {
cleaner: "eclean-dist".into(),
items: vec!["app-misc/one".into()],
unavailable: false,
});
a.recompute_digest();
let mut b = a.clone();
b.cleanup[0].items = vec!["app-misc/two".into()];
b.recompute_digest();
assert_ne!(a.digest, b.digest);
assert!(changed_materially(&a, &b));
assert!(!approval_holds(&a, &b, &[]));
let mut unavailable = a.clone();
unavailable.cleanup[0].unavailable = true;
unavailable.cleanup[0].items.clear();
unavailable.recompute_digest();
assert!(changed_materially(&a, &unavailable));
}
#[test] #[test]
fn render_states_source_binary_and_consequences() { fn render_states_source_binary_and_consequences() {
let plan = parse_emerge_pretend(PRETEND); let plan = parse_emerge_pretend(PRETEND);

View file

@ -6,11 +6,8 @@
use std::path::Path; use std::path::Path;
use phoebus_core::action::SystemAction; use phoebus_core::action::SystemAction;
use phoebus_core::effects::{ use phoebus_core::effects::{changed_materially, parse_emerge_pretend, ResolvedPlan};
changed_materially, parse_emerge_pretend, CleanupEffect, EffectKind, EffectSource, use phoebus_core::selection::Need;
PackageEffect, ResolvedPlan,
};
use phoebus_core::selection::{Backend, Need};
use phoebus_core::transaction::TransactionOutcome; use phoebus_core::transaction::TransactionOutcome;
use crate::auth::DestructiveAuthorization; use crate::auth::DestructiveAuthorization;
@ -71,7 +68,7 @@ pub(crate) fn is_host_root(root: &Path) -> bool {
/// root, or inside the target chroot for an alternate root. This is the single /// root, or inside the target chroot for an alternate root. This is the single
/// place package, service and Flatpak commands are rooted, so preview and /// place package, service and Flatpak commands are rooted, so preview and
/// execution always target the same system. /// execution always target the same system.
pub(crate) fn target_spec( fn target_spec(
root: &Path, root: &Path,
stage: &str, stage: &str,
operation: &str, operation: &str,
@ -179,37 +176,81 @@ fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
} }
} }
/// Whether [`resolve_effects`] produces a real, comparable plan for an action. /// Whether [`resolve_effects`] produces a real, comparable package plan for an
/// /// action. Only Portage transactions have `emerge --pretend` effects; other
/// Portage transactions resolve from `emerge --pretend`; the maintenance /// lanes' effects are resolved by the install layer. Callers that compare a
/// actions (depclean, per-source updates, cache cleanup) resolve a structured, /// re-resolution against a reviewed plan must use this to avoid treating a
/// digest-bound plan too. Callers that compare a re-resolution against a /// "no comparable package plan" result as a material change.
/// reviewed plan must use this to avoid treating a "no comparable plan" result
/// as material drift.
pub fn resolves_effects(action: &SystemAction) -> bool { pub fn resolves_effects(action: &SystemAction) -> bool {
pretend_args(action).is_some() pretend_args(action).is_some()
|| matches!(
action,
SystemAction::Depclean
| SystemAction::ApplyUpdates { .. }
| SystemAction::CleanCache { .. }
)
} }
/// Resolve exactly what a package or maintenance action will do. A plan's /// Resolve exactly what a package action will do. Non-Portage actions yield an
/// digest is bound to the approval and re-checked immediately before execution. /// empty plan. A plan's digest can be bound to an approval.
pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result<ResolvedPlan> { pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result<ResolvedPlan> {
action action
.validate() .validate()
.map_err(|e| ExecError::operation("sys", "validate action", e))?; .map_err(|e| ExecError::operation("sys", "validate action", e))?;
// Destructive maintenance and Portage updates are previewed from a real
// `--pretend`, so approval binds to exactly what will happen. Other lanes
// resolve their effects in the install layer.
match action { match action {
SystemAction::Depclean => return resolve_depclean_effects(exec, root), SystemAction::Depclean => {
SystemAction::ApplyUpdates { backend } => { let spec = target_spec(
return resolve_update_effects(exec, root, *backend); root,
"sys",
"resolve depclean",
"emerge",
&["--pretend".into(), "--depclean".into(), "--color=n".into()],
);
let out = exec.run_capture(spec)?;
let mut plan = ResolvedPlan::default();
plan.established = true;
plan.consequences.push(format!(
"depclean would remove:\n{}",
out.stdout_lossy().trim()
));
plan.recompute_digest();
return Ok(plan);
} }
SystemAction::CleanCache { backend } => { SystemAction::ApplyUpdates { backend }
return resolve_cleanup_effects(exec, root, *backend); if backend.map(|b| b.is_portage()).unwrap_or(true) =>
{
let spec = target_spec(
root,
"sys",
"resolve updates",
"emerge",
&[
"--pretend".into(),
"--update".into(),
"--deep".into(),
"--newuse".into(),
"--color=n".into(),
"--".into(),
"@world".into(),
],
);
let out = exec.run_capture(spec)?;
let mut plan = parse_emerge_pretend(&out.stdout_lossy());
if !plan.established {
return Err(ExecError::operation(
"sys",
"resolve updates",
"could not establish the update plan from emerge --pretend; \
refusing to proceed unreviewed",
));
}
if backend.is_none() {
plan.consequences.push(
"Flatpak/Snap/AppImage/Nix updates are applied per source and are not \
predicted in this Portage preview"
.into(),
);
}
plan.recompute_digest();
return Ok(plan);
} }
_ => {} _ => {}
} }
@ -238,7 +279,7 @@ pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Resul
if plan if plan
.effects .effects
.iter() .iter()
.any(|e| e.source == EffectSource::Source) .any(|e| e.source == phoebus_core::effects::EffectSource::Source)
{ {
return Err(ExecError::operation( return Err(ExecError::operation(
"sys", "sys",
@ -255,419 +296,6 @@ pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Resul
Ok(plan) Ok(plan)
} }
/// Depclean removals are parsed into structured effects, not only prose, so a
/// changed removal set changes the approved digest and is caught before
/// execution.
fn resolve_depclean_effects(exec: &Exec, root: &Path) -> Result<ResolvedPlan> {
let spec = target_spec(
root,
"sys",
"resolve depclean",
"emerge",
&["--pretend".into(), "--depclean".into(), "--color=n".into()],
);
let out = exec.run_capture(spec)?;
let mut plan = parse_emerge_pretend(&out.stdout_lossy());
if !plan.established {
return Err(ExecError::operation(
"sys",
"resolve depclean",
"could not establish the depclean selection from emerge --pretend; \
refusing to proceed unreviewed",
));
}
if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
plan.recovery_point = Some("a protective snapshot before the change".into());
}
plan.recompute_digest();
Ok(plan)
}
pub(crate) fn update_limitation(backend: Backend) -> &'static str {
match backend {
Backend::Nix => {
"Nix packages are declarative/pinned; update them in their project or profile"
}
Backend::AppImage => {
"managed AppImages have no update repository; re-acquire with a pinned URL + SHA-256"
}
Backend::CustomEbuild => "rebuild the staged ebuild through Portage explicitly",
_ => "this source has no system-level update transaction",
}
}
/// The flatpak client must answer in the intended target.
fn flatpak_available(exec: &Exec, root: &Path) -> bool {
crate::query::flatpak_available(exec, root)
}
/// Exact per-application Flatpak update effects. Each affected application is
/// an identity plus its planned new version, so approval cannot authorize an
/// unrestricted update-all.
fn flatpak_update_effects(exec: &Exec, root: &Path) -> Result<Vec<PackageEffect>> {
if !flatpak_available(exec, root) {
return Err(ExecError::operation(
"sys",
"resolve flatpak updates",
"the Flatpak client is not available in the target",
));
}
let updates = exec
.runner
.execute(&target_spec(
root,
"sys",
"resolve flatpak updates",
"flatpak",
&[
"remote-ls".into(),
"--updates".into(),
"--columns=application,version,branch".into(),
],
))
.map_err(|e| {
ExecError::operation(
"sys",
"resolve flatpak updates",
format!("flatpak remote-ls could not run: {e}"),
)
})?;
if !updates.success {
return Err(ExecError::operation(
"sys",
"resolve flatpak updates",
format!(
"flatpak remote-ls failed: {}",
updates.stderr_lossy().trim()
),
));
}
let mut current = std::collections::BTreeMap::new();
if let Ok(list) = exec.runner.execute(&target_spec(
root,
"sys",
"resolve flatpak updates",
"flatpak",
&[
"list".into(),
"--app".into(),
"--columns=application,version".into(),
],
)) {
if list.success {
for line in list.stdout_lossy().lines() {
let mut parts = line.split_whitespace();
if let (Some(id), Some(version)) = (parts.next(), parts.next()) {
current.insert(id.to_string(), version.to_string());
}
}
}
}
let mut effects = Vec::new();
for line in updates.stdout_lossy().lines() {
let mut parts = line.split_whitespace();
let (Some(id), Some(new_version)) = (parts.next(), parts.next()) else {
continue;
};
if id.is_empty() || new_version.is_empty() {
continue;
}
effects.push(PackageEffect {
target: format!("{id}-{new_version}"),
previous: current.get(id).cloned(),
kind: EffectKind::Upgrade,
source: EffectSource::Binary,
});
}
Ok(effects)
}
/// Exact per-snap update effects. Snaps act on the running daemon, so an
/// alternate root is refused before any command is issued.
fn snap_update_effects(exec: &Exec, root: &Path) -> Result<Vec<PackageEffect>> {
if !is_host_root(root) {
return Err(ExecError::operation(
"sys",
"resolve snap updates",
"Snap acts on the running daemon and cannot be redirected to an alternate root; \
refusing to touch the host",
));
}
let status = snap::status(exec)?;
if !status.usable() {
return Err(ExecError::operation(
"sys",
"resolve snap updates",
"snapd is not installed or active",
));
}
let updates = exec.runner.execute(
&CommandSpec::new("sys", "resolve snap updates", "snap").args(["refresh", "--list"]),
)?;
if !updates.success {
return Err(ExecError::operation(
"sys",
"resolve snap updates",
format!(
"snap refresh --list failed: {}",
updates.stderr_lossy().trim()
),
));
}
let mut current = std::collections::BTreeMap::new();
if let Ok(entries) = snap::list(exec) {
for entry in entries {
current.insert(entry.name, entry.version);
}
}
let mut effects = Vec::new();
for line in updates.stdout_lossy().lines().skip(1) {
let mut parts = line.split_whitespace();
let (Some(name), Some(new_version)) = (parts.next(), parts.next()) else {
continue;
};
if name.is_empty() || new_version.is_empty() {
continue;
}
effects.push(PackageEffect {
target: format!("{name}-{new_version}"),
previous: current.get(name).cloned(),
kind: EffectKind::Upgrade,
source: EffectSource::Binary,
});
}
Ok(effects)
}
/// Resolve a reviewable, per-source update plan. Each lane contributes exact
/// affected identities (and versions where the backend reports them). A lane
/// that cannot be updated deterministically is refused when explicitly
/// requested, never silently skipped.
fn resolve_update_effects(
exec: &Exec,
root: &Path,
backend: Option<Backend>,
) -> Result<ResolvedPlan> {
let lanes: Vec<Backend> = match backend {
Some(backend) => vec![backend],
None => vec![Backend::PortageSource, Backend::Flatpak, Backend::Snap],
};
let mut plan = ResolvedPlan {
established: true,
..Default::default()
};
for lane in lanes {
if lane.is_portage() {
let spec = target_spec(
root,
"sys",
"resolve updates",
"emerge",
&[
"--pretend".into(),
"--update".into(),
"--deep".into(),
"--newuse".into(),
"--color=n".into(),
"--".into(),
"@world".into(),
],
);
let out = exec.run_capture(spec)?;
let parsed = parse_emerge_pretend(&out.stdout_lossy());
if !parsed.established {
return Err(ExecError::operation(
"sys",
"resolve updates",
"could not establish the update plan from emerge --pretend; \
refusing to proceed unreviewed",
));
}
plan.effects.extend(parsed.effects);
if let Some(bytes) = parsed.download_bytes {
*plan.download_bytes.get_or_insert(0) += bytes;
}
plan.consequences.extend(parsed.consequences);
} else if lane == Backend::Flatpak {
match flatpak_update_effects(exec, root) {
Ok(effects) => plan.effects.extend(effects),
Err(e) if backend.is_none() => plan
.consequences
.push(format!("[flatpak] updates could not be resolved: {e}")),
Err(e) => return Err(e),
}
} else if lane == Backend::Snap {
match snap_update_effects(exec, root) {
Ok(effects) => plan.effects.extend(effects),
Err(e) if backend.is_none() => plan
.consequences
.push(format!("[snap] updates could not be resolved: {e}")),
Err(e) => return Err(e),
}
} else {
// Not in the default set; only reachable when explicitly requested.
return Err(ExecError::operation(
"sys",
"resolve updates",
format!(
"{} updates cannot be applied safely by `sys`: {}",
lane.as_str(),
update_limitation(lane)
),
));
}
}
if backend.is_none() {
plan.consequences.push(
"Nix, managed AppImages and custom ebuilds are project- or format-specific and are \
not part of this update transaction"
.into(),
);
}
if plan.effects.is_empty() {
plan.consequences.push("no updates are available".into());
}
if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
plan.recovery_point = Some("a protective snapshot before the change".into());
}
plan.recompute_digest();
Ok(plan)
}
/// The cache cleaners for a lane, as `(cleaner, dry-run args, destructive args)`.
pub(crate) fn portage_cleaners(root: &Path) -> Vec<(&'static str, Vec<String>, Vec<String>)> {
let mut cleaners = Vec::new();
if crate::exec::tool_in_target(root, "eclean-dist") {
cleaners.push(("eclean-dist", vec![], vec!["-d".to_string()]));
}
if crate::exec::tool_in_target(root, "eclean-pkg") {
cleaners.push(("eclean-pkg", vec![], vec!["-d".to_string()]));
}
cleaners
}
/// Resolve a reviewable cache-cleanup plan from non-destructive dry runs. A
/// cleaner that cannot run is recorded as unavailable, distinct from one that
/// ran and found nothing.
fn resolve_cleanup_effects(
exec: &Exec,
root: &Path,
backend: Option<Backend>,
) -> Result<ResolvedPlan> {
let lanes: Vec<Backend> = match backend {
Some(backend) => vec![backend],
None => vec![Backend::PortageSource, Backend::Nix],
};
let mut plan = ResolvedPlan {
established: true,
..Default::default()
};
for lane in lanes {
if lane.is_portage() {
for (cleaner, dry_args, _) in portage_cleaners(root) {
let out = exec.runner.execute(&target_spec(
root,
"sys",
"resolve cache cleanup",
cleaner,
&dry_args,
));
match out {
Ok(output) if output.success => {
let items = output
.stdout_lossy()
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect();
plan.cleanup.push(CleanupEffect {
cleaner: cleaner.to_string(),
items,
unavailable: false,
});
}
Ok(output) => {
return Err(ExecError::operation(
"sys",
"resolve cache cleanup",
format!("{cleaner} dry run failed: {}", output.stderr_lossy().trim()),
));
}
Err(e) => {
return Err(ExecError::operation(
"sys",
"resolve cache cleanup",
format!("{cleaner} dry run could not run: {e}"),
));
}
}
}
} else if lane == Backend::Nix {
if !crate::nix::installed(root) {
plan.cleanup.push(CleanupEffect {
cleaner: "nix-store --gc".into(),
items: Vec::new(),
unavailable: true,
});
} else {
let out = exec.runner.execute(&target_spec(
root,
"sys",
"resolve cache cleanup",
"/nix/var/nix/profiles/default/bin/nix-store",
&["--gc".into(), "--dry-run".into()],
));
match out {
Ok(output) if output.success => {
let items = output
.stdout_lossy()
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect();
plan.cleanup.push(CleanupEffect {
cleaner: "nix-store --gc".into(),
items,
unavailable: false,
});
}
Ok(output) => {
return Err(ExecError::operation(
"sys",
"resolve cache cleanup",
format!("nix-store --gc failed: {}", output.stderr_lossy().trim()),
));
}
Err(e) => {
return Err(ExecError::operation(
"sys",
"resolve cache cleanup",
format!("nix-store --gc could not run: {e}"),
));
}
}
}
} else {
return Err(ExecError::operation(
"sys",
"resolve cache cleanup",
format!(
"the {} lane has no package cache to clean; refusing",
lane.as_str()
),
));
}
}
if plan.cleanup.is_empty() {
plan.consequences
.push("no cache cleaner is available in the target".into());
}
plan.recompute_digest();
Ok(plan)
}
/// Execute an action after re-resolving it against the approved digest. If the /// Execute an action after re-resolving it against the approved digest. If the
/// plan changed materially since review, execution is refused. /// plan changed materially since review, execution is refused.
pub fn execute_checked( pub fn execute_checked(
@ -1847,17 +1475,15 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
} }
#[test] #[test]
fn depclean_is_previewed_as_structured_removals_at_review() { fn depclean_is_previewed_from_pretend_at_review() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
runner.set_response( runner.set_response(
"emerge", "emerge",
CommandOutput { CommandOutput {
status: 0, status: 0,
success: true, success: true,
stdout: b">>> These are the packages that would be unmerged:\n\n \ stdout: b">>> These are the packages that would be unmerged:\n\
app-misc/unused\n selected: 1.0\n\n\ app-misc/unused-1.0\n\n0 packages selected\n"
All selected packages: app-misc/unused-1.0\n\n\
>>> 'Selected' packages are slated for removal.\n"
.to_vec(), .to_vec(),
stderr: Vec::new(), stderr: Vec::new(),
duration: std::time::Duration::from_millis(1), duration: std::time::Duration::from_millis(1),
@ -1866,98 +1492,11 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
let exec = make_exec(runner); let exec = make_exec(runner);
let plan = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap(); let plan = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap();
assert!(plan.established); assert!(plan.established);
// Removals are structured effects, so changing them changes the digest
// and is caught before execution.
assert_eq!(plan.removals(), 1);
assert_eq!(plan.effects[0].target, "app-misc/unused-1.0");
assert!(plan assert!(plan
.consequences .consequences
.iter() .iter()
.any(|c| c.contains("will be removed"))); .any(|c| c.contains("depclean would remove")));
assert!(plan.render().contains("app-misc/unused-1.0")); assert!(plan.render().contains("depclean would remove"));
}
#[test]
fn depclean_effect_digest_detects_a_changed_removal_set() {
let runner = RecordingRunner::new();
runner.set_response(
"emerge",
CommandOutput {
status: 0,
success: true,
stdout: b"All selected packages: app-misc/unused-1.0\n".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let exec = make_exec(runner.clone());
let approved = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap();
// The next preview selects a different package entirely.
runner.set_response(
"emerge",
CommandOutput {
status: 0,
success: true,
stdout: b"All selected packages: app-misc/other-2.0\n".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let current = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap();
assert_ne!(approved.digest, current.digest);
assert!(phoebus_core::effects::changed_materially(
&approved, &current
));
assert!(!phoebus_core::effects::approval_holds(
&approved,
&current,
&[]
));
}
#[test]
fn maintenance_actions_have_comparable_effects() {
assert!(resolves_effects(&SystemAction::Depclean));
assert!(resolves_effects(&SystemAction::ApplyUpdates {
backend: None
}));
assert!(resolves_effects(&SystemAction::ApplyUpdates {
backend: Some(phoebus_core::selection::Backend::Flatpak),
}));
assert!(resolves_effects(&SystemAction::CleanCache {
backend: None
}));
}
#[test]
fn execute_checked_refuses_depclean_drift_before_any_mutation() {
let approved_runner = RecordingRunner::new();
approved_runner.set_response(
"emerge",
response("All selected packages: app-misc/old-1.0\n"),
);
let approved_exec = make_exec(approved_runner);
let approved =
resolve_effects(&approved_exec, &SystemAction::Depclean, Path::new("/")).unwrap();
let runner = RecordingRunner::new();
runner.set_response(
"emerge",
response("All selected packages: app-misc/new-2.0\n"),
);
let exec = make_exec(runner.clone());
let auth = auth();
let err = execute_checked(
&exec,
&SystemAction::Depclean,
Some(&auth),
Path::new("/"),
Some(&approved),
)
.unwrap_err();
assert!(err.to_string().contains("plan changed"), "{err}");
// Only the re-resolution preview ran; the destructive depclean did not.
assert_eq!(runner.recorded().len(), 1, "{:?}", runner.recorded());
} }
#[test] #[test]

View file

@ -109,18 +109,6 @@ pub fn save_preferences(exec: &Exec, root: &Path, prefs: &Preferences) -> Result
save_system_preferences(exec, root, prefs) save_system_preferences(exec, root, prefs)
} }
/// Build a command rooted at the intended target: directly for the running
/// root, or inside the target chroot for an alternate root.
fn rooted(root: &Path, stage: &str, operation: &str, program: &str, args: &[&str]) -> CommandSpec {
let owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();
crate::actions::target_spec(root, stage, operation, program, &owned)
}
/// Snap acts on the running daemon and cannot be redirected to a target.
fn snap_on_host(root: &Path) -> bool {
root == Path::new("/")
}
/// Read free storage for the filesystem containing `root` using `df -Pk`. /// Read free storage for the filesystem containing `root` using `df -Pk`.
fn free_mib(exec: &Exec, root: &Path) -> u64 { fn free_mib(exec: &Exec, root: &Path) -> u64 {
let path = if root.exists() { let path = if root.exists() {
@ -178,10 +166,13 @@ pub fn hardware_facts(exec: &Exec, root: &Path) -> HardwareFacts {
if crate::nix::installed(root) { if crate::nix::installed(root) {
available_backends.insert(Backend::Nix); available_backends.insert(Backend::Nix);
} }
if crate::exec::tool_in_target(root, "flatpak") { if crate::exec::find_in_path("flatpak").is_some() {
available_backends.insert(Backend::Flatpak); available_backends.insert(Backend::Flatpak);
} }
if snap_on_host(root) && matches!(crate::snap::status(exec), Ok(status) if status.usable()) { if matches!(
crate::snap::status(exec),
Ok(status) if status.usable()
) {
available_backends.insert(Backend::Snap); available_backends.insert(Backend::Snap);
} }
@ -292,13 +283,11 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
let name = &need.name; let name = &need.name;
// --- Portage ------------------------------------------------------ // --- Portage ------------------------------------------------------
let pretend = exec.runner.execute(&rooted( let pretend = exec.runner.execute(
root, &CommandSpec::new("sys", "resolve Portage candidate", "emerge")
"sys", .args(["--pretend", "--quiet", "--color=n", "--"])
"resolve Portage candidate", .arg(name),
"emerge", );
&["--pretend", "--quiet", "--color=n", "--", name.as_str()],
));
match pretend { match pretend {
Ok(resolved) if resolved.success => { Ok(resolved) if resolved.success => {
let text = resolved.stdout_lossy(); let text = resolved.stdout_lossy();
@ -307,20 +296,11 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
.unwrap_or_else(|| (name.clone(), None)); .unwrap_or_else(|| (name.clone(), None));
out.push(portage_candidate(&atom, false, version.as_deref(), &facts)); out.push(portage_candidate(&atom, false, version.as_deref(), &facts));
if facts.binhost_available { if facts.binhost_available {
let bin_check = exec.runner.execute(&rooted( let bin_check = exec.runner.execute(
root, &CommandSpec::new("sys", "check Portage binpkg", "emerge")
"sys", .args(["--pretend", "--quiet", "--color=n", "--usepkgonly", "--"])
"check Portage binpkg", .arg(name),
"emerge", );
&[
"--pretend",
"--quiet",
"--color=n",
"--usepkgonly",
"--",
name.as_str(),
],
));
let bin_available = match bin_check { let bin_available = match bin_check {
Ok(res) if res.success => { Ok(res) if res.success => {
let out = res.stdout_lossy(); let out = res.stdout_lossy();
@ -371,7 +351,7 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
} }
// --- Flatpak ------------------------------------------------------ // --- Flatpak ------------------------------------------------------
if crate::exec::tool_in_target(root, "flatpak") { if crate::exec::find_in_path("flatpak").is_some() {
let mut c = Candidate::new(Backend::Flatpak, name, "flathub"); let mut c = Candidate::new(Backend::Flatpak, name, "flathub");
c.sandbox = SandboxLevel::Strong; c.sandbox = SandboxLevel::Strong;
c.update_reliability = UpdateReliability::Automatic; c.update_reliability = UpdateReliability::Automatic;
@ -383,13 +363,14 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
.push("not a reverse-DNS Flatpak application id".into()); .push("not a reverse-DNS Flatpak application id".into());
} else { } else {
// Confirm the id actually exists in the configured remotes. // Confirm the id actually exists in the configured remotes.
let found = exec.runner.execute(&rooted( let found = exec.runner.execute(
root, &CommandSpec::new("sys", "resolve Flatpak candidate", "flatpak").args([
"sys", "search",
"resolve Flatpak candidate", "--columns=application",
"flatpak", "--",
&["search", "--columns=application", "--", name.as_str()], name,
)); ]),
);
match found { match found {
Ok(o) if o.success && o.stdout_lossy().contains(name) => { Ok(o) if o.success && o.stdout_lossy().contains(name) => {
c.verified = true; c.verified = true;
@ -406,7 +387,7 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
} }
// --- Snap --------------------------------------------------------- // --- Snap ---------------------------------------------------------
if snap_on_host(root) && matches!(crate::snap::status(exec), Ok(s) if s.usable()) { if matches!(crate::snap::status(exec), Ok(s) if s.usable()) {
let mut c = Candidate::new(Backend::Snap, name, "Snap Store"); let mut c = Candidate::new(Backend::Snap, name, "Snap Store");
c.sandbox = SandboxLevel::Strong; c.sandbox = SandboxLevel::Strong;
c.update_reliability = UpdateReliability::Automatic; c.update_reliability = UpdateReliability::Automatic;
@ -482,26 +463,24 @@ pub fn installed_backend(exec: &Exec, root: &Path, name: &str) -> Option<Backend
if crate::appimage::info(root, name).is_ok() { if crate::appimage::info(root, name).is_ok() {
return Some(Backend::AppImage); return Some(Backend::AppImage);
} }
// Flatpak: parse the installed list in the intended target. // Flatpak: parse the installed list.
if crate::exec::tool_in_target(root, "flatpak") { if crate::exec::find_in_path("flatpak").is_some() {
if let Ok(out) = exec.runner.execute(&rooted( if let Ok(out) = exec.runner.execute(
root, &CommandSpec::new("sys", "detect installed flatpak", "flatpak").args([
"sys", "list",
"detect installed flatpak", "--app",
"flatpak", "--columns=application",
&["list", "--app", "--columns=application"], ]),
)) { ) {
if out.success && out.stdout_lossy().lines().any(|l| l.trim() == name) { if out.success && out.stdout_lossy().lines().any(|l| l.trim() == name) {
return Some(Backend::Flatpak); return Some(Backend::Flatpak);
} }
} }
} }
// Snap: parse the installed list (host only; snap has no target scope). // Snap: parse the installed list.
if snap_on_host(root) { if let Ok(entries) = crate::snap::list(exec) {
if let Ok(entries) = crate::snap::list(exec) { if entries.iter().any(|e| e.name == name) {
if entries.iter().any(|e| e.name == name) { return Some(Backend::Snap);
return Some(Backend::Snap);
}
} }
} }
// Portage: a VDB entry for the package (bare name or full atom). // Portage: a VDB entry for the package (bare name or full atom).
@ -617,47 +596,19 @@ pub fn candidate_detail(exec: &Exec, root: &Path, backend: Backend, id: &str) ->
match backend { match backend {
Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => { Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
// Declared dependencies come from authoritative metadata: the VDB if let Ok(out) = exec.runner.execute(
// when installed, otherwise `qdepends` (portage-utils). An &CommandSpec::new("sys", "inspect candidate dependencies", "emerge")
// `emerge --pretend` merge plan is deliberately not used, because it .args(["--pretend", "--quiet", "--color=n", "--"])
// describes pending merges rather than the dependency graph. .arg(id),
if let Some(record) = crate::portage::installed_packages(root) ) {
.into_iter() if out.success {
.find(|p| p.atom == id || p.atom.ends_with(&format!("/{id}"))) let plan = phoebus_core::effects::parse_emerge_pretend(&out.stdout_lossy());
{ dependencies = plan.effects.into_iter().map(|e| e.target).collect();
for text in [&record.depend, &record.rdepend, &record.bdepend]
.into_iter()
.flatten()
{
dependencies.extend(
crate::portage::parse_dependencies(text)
.into_iter()
.map(|d| d.raw),
);
}
dependencies.sort();
dependencies.dedup();
} else if crate::exec::tool_in_target(root, "qdepends") {
if let Ok(out) = exec.runner.execute(&rooted(
root,
"sys",
"inspect candidate dependencies",
"qdepends",
&["-Q", "--", id],
)) {
if out.success {
dependencies = crate::portage::parse_dependencies(&out.stdout_lossy())
.into_iter()
.map(|d| d.raw)
.collect();
}
} }
} }
} }
Backend::Snap => { Backend::Snap => {
if !snap_on_host(root) { if let Ok(out) = exec.runner.execute(
// Snap has no alternate-root scope.
} else if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "inspect snap candidate", "snap").args([ &CommandSpec::new("sys", "inspect snap candidate", "snap").args([
"info", "info",
id, id,
@ -736,14 +687,15 @@ pub fn resolve_for_backend(
match backend { match backend {
Backend::Flatpak => { Backend::Flatpak => {
if crate::exec::tool_in_target(root, "flatpak") { if crate::exec::find_in_path("flatpak").is_some() {
if let Ok(out) = exec.runner.execute(&rooted( if let Ok(out) = exec.runner.execute(
root, &CommandSpec::new("sys", "resolve flatpak name", "flatpak").args([
"sys", "search",
"resolve flatpak name", "--columns=application,version",
"flatpak", "--",
&["search", "--columns=application,version", "--", application], application,
)) { ]),
) {
if out.success { if out.success {
let mut matches: Vec<(String, String)> = Vec::new(); let mut matches: Vec<(String, String)> = Vec::new();
for line in out.stdout_lossy().lines() { for line in out.stdout_lossy().lines() {
@ -786,7 +738,7 @@ pub fn resolve_for_backend(
} }
} }
Backend::Snap => { Backend::Snap => {
if snap_on_host(root) && matches!(crate::snap::status(exec), Ok(s) if s.usable()) { if matches!(crate::snap::status(exec), Ok(s) if s.usable()) {
if let Ok(out) = exec.runner.execute( if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "resolve snap name", "snap").args([ &CommandSpec::new("sys", "resolve snap name", "snap").args([
"find", "find",
@ -819,32 +771,21 @@ pub fn resolve_for_backend(
} }
Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => { Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
// Portage resolves bare names itself; confirm the atom is real. // Portage resolves bare names itself; confirm the atom is real.
if let Ok(out) = exec.runner.execute(&rooted( if let Ok(out) = exec.runner.execute(
root, &CommandSpec::new("sys", "resolve portage name", "emerge")
"sys", .args(["--pretend", "--quiet", "--color=n", "--"])
"resolve portage name", .arg(application),
"emerge", ) {
&["--pretend", "--quiet", "--color=n", "--", application],
)) {
if out.success { if out.success {
let (atom, version) = parse_pretend_version(&out.stdout_lossy()) let (atom, version) = parse_pretend_version(&out.stdout_lossy())
.map(|v| split_atom_version(&v)) .map(|v| split_atom_version(&v))
.unwrap_or_else(|| (application.to_string(), None)); .unwrap_or_else(|| (application.to_string(), None));
if backend == Backend::PortageBinary { if backend == Backend::PortageBinary {
let bin_check = exec.runner.execute(&rooted( let bin_check = exec.runner.execute(
root, &CommandSpec::new("sys", "check Portage binpkg", "emerge")
"sys", .args(["--pretend", "--quiet", "--color=n", "--usepkgonly", "--"])
"check Portage binpkg", .arg(application),
"emerge", );
&[
"--pretend",
"--quiet",
"--color=n",
"--usepkgonly",
"--",
application,
],
));
let bin_available = match bin_check { let bin_available = match bin_check {
Ok(res) if res.success => { Ok(res) if res.success => {
let out = res.stdout_lossy(); let out = res.stdout_lossy();
@ -946,10 +887,10 @@ pub fn backend_status(exec: &Exec, root: &Path, backend: Backend) -> BackendStat
let available = facts.backend_available(backend); let available = facts.backend_available(backend);
let detail = match backend { let detail = match backend {
Backend::PortageSource | Backend::PortageVendor => { Backend::PortageSource | Backend::PortageVendor => {
if crate::exec::tool_in_target(root, "emerge") { if crate::exec::find_in_path("emerge").is_some() {
"Portage (emerge) is present".into() "Portage (emerge) is present".into()
} else { } else {
"emerge is not available in the target".into() "emerge is not in PATH".into()
} }
} }
Backend::PortageBinary => { Backend::PortageBinary => {
@ -967,27 +908,21 @@ pub fn backend_status(exec: &Exec, root: &Path, backend: Backend) -> BackendStat
} }
} }
Backend::Flatpak => { Backend::Flatpak => {
if crate::exec::tool_in_target(root, "flatpak") { if crate::exec::find_in_path("flatpak").is_some() {
"the flatpak client is present in the target".into() "the flatpak client is present".into()
} else { } else {
"flatpak is not available in the target".into() "flatpak is not installed".into()
}
}
Backend::Snap => {
if !snap_on_host(root) {
"Snap cannot be inspected for an alternate root".into()
} else {
match crate::snap::status(exec) {
Ok(s) => format!(
"snap client present: {}, daemon active: {}, confinement: {}",
s.client_present,
s.daemon_ready,
s.confinement.as_str()
),
Err(_) => "snapd state could not be determined".into(),
}
} }
} }
Backend::Snap => match crate::snap::status(exec) {
Ok(s) => format!(
"snap client present: {}, daemon active: {}, confinement: {}",
s.client_present,
s.daemon_ready,
s.confinement.as_str()
),
Err(_) => "snapd state could not be determined".into(),
},
Backend::AppImage => "AppImages can be imported or downloaded locally".into(), Backend::AppImage => "AppImages can be imported or downloaded locally".into(),
Backend::CustomEbuild => { Backend::CustomEbuild => {
if crate::ebuild::list(root).is_empty() { if crate::ebuild::list(root).is_empty() {
@ -1004,39 +939,20 @@ pub fn backend_status(exec: &Exec, root: &Path, backend: Backend) -> BackendStat
} }
} }
/// Whether a lane is covered by an optional source filter.
fn lane_selected(filter: Option<Backend>, lane: Backend) -> bool {
match filter {
Some(f) => f == lane || (f.is_portage() && lane.is_portage()),
None => true,
}
}
/// Inspect what is already installed for an application across lanes. Never /// Inspect what is already installed for an application across lanes. Never
/// invents a copy; every entry comes from a real backend inventory. /// invents a copy; every entry comes from a real backend inventory.
pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> InstallationInspection { pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> InstallationInspection {
installed_copies_filtered(exec, root, application, None)
}
/// Like [`installed_copies`], but an explicit lane filter skips querying every
/// other backend, so a source-constrained request never probes a foreign lane.
pub fn installed_copies_filtered(
exec: &Exec,
root: &Path,
application: &str,
filter: Option<Backend>,
) -> InstallationInspection {
let mut copies = Vec::new(); let mut copies = Vec::new();
// Flatpak (in the intended target). // Flatpak.
if lane_selected(filter, Backend::Flatpak) && crate::exec::tool_in_target(root, "flatpak") { if crate::exec::find_in_path("flatpak").is_some() {
if let Ok(out) = exec.runner.execute(&rooted( if let Ok(out) = exec.runner.execute(
root, &CommandSpec::new("sys", "inspect installed flatpaks", "flatpak").args([
"sys", "list",
"inspect installed flatpaks", "--app",
"flatpak", "--columns=application,name,version",
&["list", "--app", "--columns=application,name,version"], ]),
)) { ) {
if out.success { if out.success {
let app_lower = application.to_ascii_lowercase(); let app_lower = application.to_ascii_lowercase();
for line in out.stdout_lossy().lines() { for line in out.stdout_lossy().lines() {
@ -1076,51 +992,45 @@ pub fn installed_copies_filtered(
} }
} }
// Snap (host only). // Snap.
if lane_selected(filter, Backend::Snap) && snap_on_host(root) { if let Ok(entries) = crate::snap::list(exec) {
if let Ok(entries) = crate::snap::list(exec) { for entry in entries {
for entry in entries { if entry.name.eq_ignore_ascii_case(application) {
if entry.name.eq_ignore_ascii_case(application) { copies.push(InstalledCopy {
copies.push(InstalledCopy { backend: Backend::Snap.as_str().into(),
backend: Backend::Snap.as_str().into(), id: entry.name,
id: entry.name, version: entry.version,
version: entry.version, });
});
}
} }
} }
} }
// AppImage (managed record). // AppImage (managed record).
if lane_selected(filter, Backend::AppImage) { if let Ok(records) = crate::appimage::list(root) {
if let Ok(records) = crate::appimage::list(root) { for record in records {
for record in records { if record.name.eq_ignore_ascii_case(application) {
if record.name.eq_ignore_ascii_case(application) { copies.push(InstalledCopy {
copies.push(InstalledCopy { backend: Backend::AppImage.as_str().into(),
backend: Backend::AppImage.as_str().into(), id: record.name,
id: record.name, version: record.version,
version: record.version, });
});
}
} }
} else if let Ok(record) = crate::appimage::info(root, application) {
copies.push(InstalledCopy {
backend: Backend::AppImage.as_str().into(),
id: record.name,
version: record.version,
});
} }
} else if let Ok(record) = crate::appimage::info(root, application) {
copies.push(InstalledCopy {
backend: Backend::AppImage.as_str().into(),
id: record.name,
version: record.version,
});
} }
// Portage (VDB). // Portage (VDB).
if lane_selected(filter, Backend::PortageSource) { if let Some((atom, version)) = portage_installed_atom_and_version(root, application) {
if let Some((atom, version)) = portage_installed_atom_and_version(root, application) { copies.push(InstalledCopy {
copies.push(InstalledCopy { backend: Backend::PortageSource.as_str().into(),
backend: Backend::PortageSource.as_str().into(), id: atom,
id: atom, version,
version, });
});
}
} }
// De-duplicate any multiple matches within the same backend // De-duplicate any multiple matches within the same backend
@ -1251,13 +1161,11 @@ mod tests {
#[test] #[test]
fn portage_candidate_keeps_a_valid_install_atom() { fn portage_candidate_keeps_a_valid_install_atom() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
// An alternate root runs Portage inside the target chroot; the mock
// runner therefore answers the `chroot` wrapper.
runner.set_response( runner.set_response(
"chroot", "emerge",
ok("Calculating dependencies... done!\n[ebuild N ] app-misc/hello-2.12.3 USE=\"nls\"\n"), ok("Calculating dependencies... done!\n[ebuild N ] app-misc/hello-2.12.3 USE=\"nls\"\n"),
); );
let exec = make_exec(runner.clone()); let exec = make_exec(runner);
let root = tempfile::tempdir().unwrap(); let root = tempfile::tempdir().unwrap();
let need = Need::new("app-misc/hello"); let need = Need::new("app-misc/hello");
let candidates = resolve_candidates(&exec, root.path(), &need); let candidates = resolve_candidates(&exec, root.path(), &need);
@ -1269,13 +1177,6 @@ mod tests {
assert_eq!(portage.version.as_deref(), Some("2.12.3")); assert_eq!(portage.version.as_deref(), Some("2.12.3"));
// And the id is a valid package spec that emerge accepts. // And the id is a valid package spec that emerge accepts.
assert!(phoebus_core::action::valid_package_spec(&portage.id)); assert!(phoebus_core::action::valid_package_spec(&portage.id));
// The query must have been rooted in the target, never the host.
let recorded = runner.recorded();
let emerge = recorded
.iter()
.find(|s| s.program == "chroot" && s.args.iter().any(|a| a == "emerge"))
.expect("a chrooted emerge");
assert_eq!(emerge.args[0], root.path().to_string_lossy());
} }
#[test] #[test]
@ -1354,7 +1255,7 @@ mod tests {
fn resolve_includes_a_portage_candidate_from_real_metadata() { fn resolve_includes_a_portage_candidate_from_real_metadata() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
runner.set_response( runner.set_response(
"chroot", "emerge",
ok("Calculating dependencies... done!\n[ebuild N ] app-editors/vim-9.1.0\n"), ok("Calculating dependencies... done!\n[ebuild N ] app-editors/vim-9.1.0\n"),
); );
let exec = make_exec(runner); let exec = make_exec(runner);
@ -1369,7 +1270,7 @@ mod tests {
#[test] #[test]
fn unresolved_portage_candidate_is_marked_unavailable() { fn unresolved_portage_candidate_is_marked_unavailable() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
runner.fail("chroot", "no such package"); runner.fail("emerge", "no such package");
let exec = make_exec(runner); let exec = make_exec(runner);
let root = tempfile::tempdir().unwrap(); let root = tempfile::tempdir().unwrap();
let need = Need::new("not-a-real-package"); let need = Need::new("not-a-real-package");
@ -1412,22 +1313,13 @@ mod tests {
#[test] #[test]
fn installed_copies_reports_duplication_and_versions() { fn installed_copies_reports_duplication_and_versions() {
use std::os::unix::fs::PermissionsExt;
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
runner.set_response("chroot", ok("org.mozilla.firefox\tFirefox\t128\n")); runner.set_response("flatpak", ok("org.mozilla.firefox 128\n"));
let exec = make_exec(runner.clone()); let exec = make_exec(runner);
let root = tempfile::tempdir().unwrap(); let root = tempfile::tempdir().unwrap();
// A Flatpak present only in the target must be discovered there.
let bin = root.path().join("usr/bin");
std::fs::create_dir_all(&bin).unwrap();
let flatpak = bin.join("flatpak");
std::fs::write(&flatpak, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap();
let inspection = installed_copies(&exec, root.path(), "org.mozilla.firefox"); let inspection = installed_copies(&exec, root.path(), "org.mozilla.firefox");
assert_eq!(inspection.copies.len(), 1); assert_eq!(inspection.copies.len(), 1);
assert_eq!(inspection.copies[0].version, "128"); assert_eq!(inspection.copies[0].version, "128");
assert!(!inspection.duplicate); assert!(!inspection.duplicate);
// The target Flatpak, not the host's, was queried.
assert_eq!(runner.recorded()[0].program, "chroot");
} }
} }

View file

@ -181,28 +181,6 @@ impl Exec {
} }
} }
/// Whether a tool is present in the intended target.
///
/// For the running root this is the host `PATH`. For an alternate root a query
/// runs inside the target chroot, so availability must be resolved from the
/// target's own binary directories rather than the host's, where a host tool
/// would otherwise leak into (or bypass) target operations.
pub fn tool_in_target(root: &Path, program: &str) -> bool {
if program.contains('/') {
let candidate = root.join(program.trim_start_matches('/'));
return is_executable(&candidate);
}
if root == Path::new("/") {
return find_in_path(program).is_some();
}
for dir in ["usr/bin", "usr/sbin", "usr/local/bin", "bin", "sbin"] {
if is_executable(&root.join(dir).join(program)) {
return true;
}
}
false
}
pub fn find_in_path(program: &str) -> Option<PathBuf> { pub fn find_in_path(program: &str) -> Option<PathBuf> {
if program.contains('/') { if program.contains('/') {
let p = PathBuf::from(program); let p = PathBuf::from(program);

View file

@ -903,19 +903,13 @@ mod tests {
#[test] #[test]
fn validation_detects_an_ambiguous_friendly_name() { fn validation_detects_an_ambiguous_friendly_name() {
use std::os::unix::fs::PermissionsExt;
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
runner.set_response( runner.set_response(
"chroot", "flatpak",
ok("org.mozilla.firefox 128 stable\norg.mozilla.firefoxpwa 1.0 stable\n"), ok("org.mozilla.firefox 128 stable\norg.mozilla.firefoxpwa 1.0 stable\n"),
); );
let exec = make_exec(runner); let exec = make_exec(runner);
let root = tempfile::tempdir().unwrap(); let root = tempfile::tempdir().unwrap();
let bin = root.path().join("usr/bin");
std::fs::create_dir_all(&bin).unwrap();
let flatpak = bin.join("flatpak");
std::fs::write(&flatpak, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap();
let request = InstallRequest::new("firefox"); let request = InstallRequest::new("firefox");
let proposal = InstallProposal { let proposal = InstallProposal {
application: "firefox".into(), application: "firefox".into(),
@ -978,33 +972,23 @@ mod tests {
duration: Duration::from_millis(1), duration: Duration::from_millis(1),
}; };
let version = self.version.load(std::sync::atomic::Ordering::SeqCst); let version = self.version.load(std::sync::atomic::Ordering::SeqCst);
let is_flatpak = spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak"); match spec.program.as_str() {
let is_emerge = spec.program == "emerge" || spec.args.iter().any(|a| a == "emerge"); "flatpak" if spec.args.iter().any(|a| a == "search") => {
if is_flatpak && spec.args.iter().any(|a| a == "search") { Ok(ok(format!("org.mozilla.firefox {version}\n")))
Ok(ok(format!("org.mozilla.firefox {version}\n"))) }
} else if is_flatpak && spec.args.iter().any(|a| a == "list") { "flatpak" if spec.args.iter().any(|a| a == "list") => Ok(ok(if self.installed {
Ok(ok(if self.installed {
format!("org.mozilla.firefox {version}\n") format!("org.mozilla.firefox {version}\n")
} else { } else {
String::new() String::new()
})) })),
} else if is_emerge { "emerge" => Ok(fail()),
Ok(fail()) _ => Ok(ok(String::new())),
} else {
Ok(ok(String::new()))
} }
} }
} }
fn arg_exec(version: std::sync::Arc<std::sync::atomic::AtomicU32>, installed: bool) -> Exec { fn arg_exec(version: std::sync::Arc<std::sync::atomic::AtomicU32>, installed: bool) -> Exec {
use std::os::unix::fs::PermissionsExt;
let path = tempfile::tempdir().unwrap().keep(); let path = tempfile::tempdir().unwrap().keep();
// A Flatpak must be present in the *target* for the lane to resolve.
let bin = path.join("root/usr/bin");
std::fs::create_dir_all(&bin).unwrap();
let flatpak = bin.join("flatpak");
std::fs::write(&flatpak, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false); let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new( Exec::new(
Box::new(ArgRunner::new(version, installed)), Box::new(ArgRunner::new(version, installed)),
@ -1060,12 +1044,19 @@ mod tests {
fn ai_unqualified_install_is_confirmed_by_the_resolver() { fn ai_unqualified_install_is_confirmed_by_the_resolver() {
let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128)); let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128));
let exec = arg_exec(version, false); let exec = arg_exec(version, false);
let root = Path::new(&exec.root); let root = tempfile::tempdir().unwrap();
let request = InstallRequest::new("firefox"); let request = InstallRequest::new("firefox");
let transport = let transport =
phoebus_ai::provider::ScriptedTransport::new(vec![proposal("org.mozilla.firefox")]); phoebus_ai::provider::ScriptedTransport::new(vec![proposal("org.mozilla.firefox")]);
let resolved = let resolved = resolve_with_ai(
resolve_with_ai(&exec, root, &request, &NoAsk, &ai(&transport), &facts()).unwrap(); &exec,
root.path(),
&request,
&NoAsk,
&ai(&transport),
&facts(),
)
.unwrap();
assert_eq!(resolved.candidate.id, "org.mozilla.firefox"); assert_eq!(resolved.candidate.id, "org.mozilla.firefox");
assert_eq!(resolved.source, InstallSource::AiRecommendation); assert_eq!(resolved.source, InstallSource::AiRecommendation);
assert!(matches!( assert!(matches!(
@ -1078,14 +1069,21 @@ mod tests {
fn a_fabricated_candidate_is_rejected_and_the_model_revises() { fn a_fabricated_candidate_is_rejected_and_the_model_revises() {
let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128)); let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128));
let exec = arg_exec(version, false); let exec = arg_exec(version, false);
let root = Path::new(&exec.root); let root = tempfile::tempdir().unwrap();
let request = InstallRequest::new("firefox"); let request = InstallRequest::new("firefox");
let transport = phoebus_ai::provider::ScriptedTransport::new(vec![ let transport = phoebus_ai::provider::ScriptedTransport::new(vec![
proposal("org.evil.Firefox"), proposal("org.evil.Firefox"),
proposal("org.mozilla.firefox"), proposal("org.mozilla.firefox"),
]); ]);
let resolved = let resolved = resolve_with_ai(
resolve_with_ai(&exec, root, &request, &NoAsk, &ai(&transport), &facts()).unwrap(); &exec,
root.path(),
&request,
&NoAsk,
&ai(&transport),
&facts(),
)
.unwrap();
assert_eq!(resolved.candidate.id, "org.mozilla.firefox"); assert_eq!(resolved.candidate.id, "org.mozilla.firefox");
// The second request carries the resolver's finding. // The second request carries the resolver's finding.
assert!(transport.requests()[1].contains("no available")); assert!(transport.requests()[1].contains("no available"));
@ -1095,19 +1093,19 @@ mod tests {
fn a_changed_candidate_version_invalidates_the_review() { fn a_changed_candidate_version_invalidates_the_review() {
let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128)); let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128));
let exec = arg_exec(version.clone(), false); let exec = arg_exec(version.clone(), false);
let root = Path::new(&exec.root); let root = tempfile::tempdir().unwrap();
let mut request = InstallRequest::new("firefox"); let mut request = InstallRequest::new("firefox");
request.backend = Some(Backend::Flatpak); request.backend = Some(Backend::Flatpak);
let resolved = resolve_explicit(&exec, root, &request).unwrap(); let resolved = resolve_explicit(&exec, root.path(), &request).unwrap();
assert_eq!(resolved.candidate.version.as_deref(), Some("128")); assert_eq!(resolved.candidate.version.as_deref(), Some("128"));
// Same metadata -> the reviewed digest revalidates. // Same metadata -> the reviewed digest revalidates.
assert_eq!( assert_eq!(
revalidate(&exec, root, &resolved).unwrap(), revalidate(&exec, root.path(), &resolved).unwrap(),
resolved.approval_digest() resolved.approval_digest()
); );
// The remote publishes a new version: the approval is invalidated. // The remote publishes a new version: the approval is invalidated.
version.store(129, std::sync::atomic::Ordering::SeqCst); version.store(129, std::sync::atomic::Ordering::SeqCst);
let err = revalidate(&exec, root, &resolved).unwrap_err(); let err = revalidate(&exec, root.path(), &resolved).unwrap_err();
assert!(err.to_string().contains("version changed"), "{err}"); assert!(err.to_string().contains("version changed"), "{err}");
} }
@ -1115,10 +1113,10 @@ mod tests {
fn an_already_installed_app_in_the_same_lane_is_not_reinstalled() { fn an_already_installed_app_in_the_same_lane_is_not_reinstalled() {
let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128)); let version = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(128));
let exec = arg_exec(version, true); let exec = arg_exec(version, true);
let root = Path::new(&exec.root); let root = tempfile::tempdir().unwrap();
let mut request = InstallRequest::new("org.mozilla.firefox"); let mut request = InstallRequest::new("org.mozilla.firefox");
request.backend = Some(Backend::Flatpak); request.backend = Some(Backend::Flatpak);
let err = resolve_explicit(&exec, root, &request).unwrap_err(); let err = resolve_explicit(&exec, root.path(), &request).unwrap_err();
assert!(err.to_string().contains("already installed"), "{err}"); assert!(err.to_string().contains("already installed"), "{err}");
} }

View file

@ -304,242 +304,6 @@ pub fn profiles(root: &Path) -> Vec<NixProfile> {
out out
} }
/// One package installed in an active Nix profile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NixInstalledPackage {
/// The nixpkgs attribute path when the manifest records one (e.g.
/// `legacyPackages.x86_64-linux.nodejs`), otherwise the store name.
pub path: String,
/// The package identity (the last attribute component, or the store name).
pub name: String,
pub version: Option<String>,
pub store_path: String,
/// Human label for the profile: `default`, `profile`, or `per-user:<user>`.
pub profile: String,
pub user: Option<String>,
}
/// The result of reading active Nix profiles. `notes` records unsupported
/// profile formats and base profiles so an incomplete enumeration is never
/// presented as complete.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NixProfileInventory {
pub packages: Vec<NixInstalledPackage>,
pub notes: Vec<String>,
}
/// The active (current-generation) profile links in the target.
///
/// Only the `default` and `profile` links are current: the historical
/// `profile-N-link` generations are deliberately not counted as installed
/// packages.
fn active_profile_links(root: &Path) -> Vec<(String, Option<String>, PathBuf)> {
let base = target_path(root, "nix/var/nix/profiles");
let mut out = Vec::new();
for name in ["default", "profile"] {
let path = base.join(name);
if path.symlink_metadata().is_ok() {
out.push((name.to_string(), None, path));
}
}
let per_user = base.join("per-user");
if let Ok(users) = std::fs::read_dir(&per_user) {
for user in users.flatten() {
if !user.file_type().map(|t| t.is_dir()).unwrap_or(false) {
continue;
}
let user_name = user.file_name().to_string_lossy().to_string();
let path = user.path().join("profile");
if path.symlink_metadata().is_ok() {
out.push((format!("per-user:{user_name}"), Some(user_name), path));
}
}
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// Extract `(name, version)` from a store basename like
/// `abc123-nodejs-22.11.0` or `abc123-nodejs`.
fn store_name_parts(basename: &str) -> (String, Option<String>) {
let rest = basename
.split_once('-')
.map(|(_, rest)| rest)
.unwrap_or(basename)
.to_string();
let Some(idx) = rest
.char_indices()
.filter(|(i, c)| *c == '-' && rest[i + 1..].starts_with(|d: char| d.is_ascii_digit()))
.map(|(i, _)| i)
.next_back()
else {
return (rest, None);
};
let (name, version) = rest.split_at(idx);
(
name.to_string(),
Some(version.trim_start_matches('-').to_string()),
)
}
/// Parse a `nix profile` `manifest.json`. Returns an error string for an
/// unsupported/undecodable format so the caller can say so explicitly.
pub fn parse_manifest(
profile: &str,
user: Option<&str>,
text: &str,
) -> std::result::Result<Vec<NixInstalledPackage>, String> {
let value: serde_json::Value =
serde_json::from_str(text).map_err(|e| format!("manifest is not JSON: {e}"))?;
let version = value.get("version").and_then(|v| v.as_u64());
let Some(elements) = value.get("elements") else {
return Err("manifest has no `elements`".to_string());
};
let mut out = Vec::new();
let mut push = |element: &serde_json::Value| {
if element.get("active").and_then(|v| v.as_bool()) == Some(false) {
return;
}
let attr = element
.get("attrPath")
.and_then(|v| v.as_str())
.map(str::to_string);
let store_paths: Vec<String> = element
.get("storePaths")
.and_then(|v| v.as_array())
.map(|a| {
a.iter()
.filter_map(|v| v.as_str())
.map(str::to_string)
.collect()
})
.or_else(|| {
element
.get("storePath")
.and_then(|v| v.as_str())
.map(|s| vec![s.to_string()])
})
.unwrap_or_default();
let store_path = store_paths.first().cloned().unwrap_or_default();
let basename = store_path.rsplit('/').next().unwrap_or("").to_string();
let (store_name, version) = store_name_parts(&basename);
let name = attr
.as_deref()
.and_then(|a| a.rsplit('.').next())
.map(str::to_string)
.filter(|n| !n.is_empty())
.unwrap_or_else(|| store_name.clone());
let path = attr.unwrap_or_else(|| name.clone());
out.push(NixInstalledPackage {
path,
name,
version,
store_path,
profile: profile.to_string(),
user: user.map(str::to_string),
});
};
match elements {
serde_json::Value::Array(items) => {
for element in items {
push(element);
}
}
serde_json::Value::Object(map) => {
for element in map.values() {
push(element);
}
}
_ => {
return Err(format!(
"unsupported manifest element container (version {})",
version.map(|v| v.to_string()).unwrap_or_else(|| "?".into())
))
}
}
if out.is_empty() && version.is_some_and(|v| v > 3) {
return Err(format!(
"manifest version {} is newer than supported",
version.unwrap()
));
}
Ok(out)
}
/// Enumerate the packages installed in the active Nix profiles of the target.
///
/// Historical generations and bare store paths are not packages: generations
/// are noted, and `store_path_count` reports realised store contents
/// separately. A profile whose manifest is missing or an unsupported format is
/// reported in `notes` rather than silently omitted.
pub fn installed_packages(root: &Path) -> NixProfileInventory {
let mut inventory = NixProfileInventory::default();
for (label, user, link) in active_profile_links(root) {
let Ok(resolved) = std::fs::canonicalize(&link) else {
inventory.notes.push(format!(
"profile `{label}` is a dangling link; not enumerated"
));
continue;
};
let resolved = resolved.to_string_lossy().to_string();
// Never follow a profile outside the target.
if !resolved.starts_with(&root.to_string_lossy().to_string()) {
inventory.notes.push(format!(
"profile `{label}` resolves outside the target; not enumerated"
));
continue;
}
let manifest = Path::new(&resolved).join("manifest.json");
match std::fs::read_to_string(&manifest) {
Ok(text) => match parse_manifest(&label, user.as_deref(), &text) {
Ok(mut packages) => inventory.packages.append(&mut packages),
Err(e) => inventory.notes.push(format!(
"profile `{label}` uses an unsupported manifest format ({e}); not enumerated"
)),
},
Err(_) => inventory.notes.push(format!(
"profile `{label}` has no package manifest (base/system profile); \
its packages are not listed"
)),
}
}
// Historical generations are explicitly not current packages.
let generations = historical_generation_count(root);
if generations > 0 {
inventory.notes.push(format!(
"{generations} historical profile generation(s) exist and are not counted as \
installed packages"
));
}
inventory
.packages
.sort_by(|a, b| a.name.cmp(&b.name).then(a.profile.cmp(&b.profile)));
inventory
}
fn historical_generation_count(root: &Path) -> usize {
let base = target_path(root, "nix/var/nix/profiles");
let mut count = 0;
let mut visit = |dir: &Path| {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("profile-") && name.ends_with("-link") {
count += 1;
}
}
}
};
visit(&base);
let per_user = base.join("per-user");
if let Ok(users) = std::fs::read_dir(&per_user) {
for user in users.flatten() {
visit(&user.path());
}
}
count
}
/// Number of realised store paths, if the store exists. `None` means the store /// Number of realised store paths, if the store exists. `None` means the store
/// is absent (Nix is not installed). /// is absent (Nix is not installed).
pub fn store_path_count(root: &Path) -> Option<usize> { pub fn store_path_count(root: &Path) -> Option<usize> {
@ -703,105 +467,6 @@ mod tests {
assert!(!valid_nix_attribute("a b")); assert!(!valid_nix_attribute("a b"));
} }
fn profile_manifest_v3() -> &'static str {
r#"{
"version": 3,
"elements": [
{
"active": true,
"attrPath": "legacyPackages.x86_64-linux.nodejs",
"storePaths": ["/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-nodejs-22.11.0"],
"originalUrl": "flake:nixpkgs"
},
{
"active": false,
"attrPath": "legacyPackages.x86_64-linux.gcc",
"storePaths": ["/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-gcc-13.2.0"]
}
]
}"#
}
#[test]
fn installed_packages_enumerates_supported_profiles_and_skips_inactive() {
let runner = RecordingRunner::new();
let exec = make_exec(runner, false);
let root = Path::new(&exec.root);
let store = root.join("nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-nodejs-22.11.0");
std::fs::create_dir_all(&store).unwrap();
std::fs::write(store.join("manifest.json"), profile_manifest_v3()).unwrap();
let profiles = root.join("nix/var/nix/profiles");
std::fs::create_dir_all(&profiles).unwrap();
std::os::unix::fs::symlink(&store, profiles.join("default")).unwrap();
// A historical generation must not be counted as current.
std::os::unix::fs::symlink(&store, profiles.join("profile-1-link")).unwrap();
let inventory = installed_packages(root);
assert_eq!(inventory.packages.len(), 1, "{:?}", inventory);
let pkg = &inventory.packages[0];
assert_eq!(pkg.name, "nodejs");
assert_eq!(pkg.version.as_deref(), Some("22.11.0"));
assert_eq!(pkg.profile, "default");
assert!(pkg.path.contains("nodejs"));
assert!(inventory
.notes
.iter()
.any(|n| n.contains("historical profile generation")));
}
#[test]
fn installed_packages_reports_unsupported_manifest_formats_explicitly() {
let runner = RecordingRunner::new();
let exec = make_exec(runner, false);
let root = Path::new(&exec.root);
let store = root.join("nix/store/cccccccccccccccccccccccccccccccc-future-1.0");
std::fs::create_dir_all(&store).unwrap();
std::fs::write(
store.join("manifest.json"),
r#"{"version": 99, "elements": []}"#,
)
.unwrap();
let profiles = root.join("nix/var/nix/profiles");
std::fs::create_dir_all(&profiles).unwrap();
std::os::unix::fs::symlink(&store, profiles.join("profile")).unwrap();
let inventory = installed_packages(root);
assert!(inventory.packages.is_empty());
assert!(
inventory
.notes
.iter()
.any(|n| n.contains("newer than supported")),
"{:?}",
inventory.notes
);
// A profile with no manifest is a base profile, reported distinctly.
std::fs::create_dir_all(root.join("nix/var/nix/profiles")).unwrap();
std::os::unix::fs::symlink(root.join("nix/store"), profiles.join("default")).unwrap();
let second = installed_packages(root);
assert!(
second
.notes
.iter()
.any(|n| n.contains("no package manifest")),
"{:?}",
second.notes
);
}
#[test]
fn parse_manifest_v1_store_path_is_supported() {
let text = r#"{
"version": 1,
"elements": [
{"active": true, "uri": "nixpkgs", "storePath": "/nix/store/dddd-vim-9.1.0"}
]
}"#;
let parsed = parse_manifest("default", None, text).unwrap();
assert_eq!(parsed.len(), 1);
assert_eq!(parsed[0].name, "vim");
}
#[test] #[test]
fn remove_unlinks_units_and_optionally_purges() { fn remove_unlinks_units_and_optionally_purges() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();

View file

@ -466,7 +466,6 @@ pub struct InstalledPortage {
pub repository: Option<String>, pub repository: Option<String>,
pub depend: Option<String>, pub depend: Option<String>,
pub rdepend: Option<String>, pub rdepend: Option<String>,
pub bdepend: Option<String>,
} }
/// Split `category/pkgname-1.2.3-r1` into `(category/pkgname, "1.2.3-r1")`. /// Split `category/pkgname-1.2.3-r1` into `(category/pkgname, "1.2.3-r1")`.
@ -533,7 +532,6 @@ pub fn installed_packages(root: &Path) -> Vec<InstalledPortage> {
repository: read_vdb_field(&dir, "repository"), repository: read_vdb_field(&dir, "repository"),
depend: read_vdb_field(&dir, "DEPEND"), depend: read_vdb_field(&dir, "DEPEND"),
rdepend: read_vdb_field(&dir, "RDEPEND"), rdepend: read_vdb_field(&dir, "RDEPEND"),
bdepend: read_vdb_field(&dir, "BDEPEND"),
}); });
} }
} }
@ -604,108 +602,6 @@ fn nonempty(value: &str) -> Option<String> {
} }
} }
/// One declared dependency, preserving its version/conditional context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeclaredDependency {
/// The raw token, e.g. `>=dev-libs/glib-2.0` or `cat/pkg:1`.
pub raw: String,
/// The package atom with operators, version, slot and USE stripped.
pub atom: String,
/// The USE flag/group this dependency is conditional on, if any.
pub condition: Option<String>,
/// A blocker (`!cat/pkg`).
pub negative: bool,
}
/// Tokenize a dependency string, keeping parentheses as separate tokens.
fn tokenize_depends(text: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
for c in text.chars() {
match c {
'(' | ')' => {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current));
}
tokens.push(c.to_string());
}
c if c.is_whitespace() => {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current));
}
}
c => current.push(c),
}
}
if !current.is_empty() {
tokens.push(current);
}
tokens
}
/// Normalize a dependency token to a bare `category/name` atom.
pub fn normalize_dep_atom(token: &str) -> String {
let mut t = token.trim_start_matches(['!', '?']).to_string();
// USE dependency / slot / version: keep only `category/name`.
if let Some(idx) = t.find('[') {
t.truncate(idx);
}
if let Some(idx) = t.find(':') {
t.truncate(idx);
}
for op in ["~", ">=", "<=", "=", ">", "<"] {
t = t.trim_start_matches(op).to_string();
}
if let Some((atom, _)) = split_pkgver(&t) {
atom
} else {
t
}
}
/// Parse a declared dependency string into atoms, preserving conditionals and
/// version operators. Dependencies inside a USE-conditional or any-of group
/// keep that context so the report is honest about when they apply.
pub fn parse_dependencies(text: &str) -> Vec<DeclaredDependency> {
let mut out = Vec::new();
let mut conditions: Vec<String> = Vec::new();
let mut pending: Option<String> = None;
for token in tokenize_depends(text) {
match token.as_str() {
"(" => {
let context = pending.take().unwrap_or_else(|| "group".to_string());
conditions.push(context);
}
")" => {
conditions.pop();
}
"||" => {
pending = Some("any-of".to_string());
}
"??" => {
pending = Some("any-of".to_string());
}
t if t.ends_with('?') => {
pending = Some(format!("{}?", t.trim_end_matches('?')));
}
t if t.contains('/') => {
let negative = t.starts_with('!');
let atom = normalize_dep_atom(t);
if atom.contains('/') {
out.push(DeclaredDependency {
raw: t.to_string(),
atom,
condition: conditions.last().cloned(),
negative,
});
}
}
_ => {}
}
}
out
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -903,30 +799,6 @@ mod tests {
assert!(installed_packages(Path::new(&exec.root)).is_empty()); assert!(installed_packages(Path::new(&exec.root)).is_empty());
} }
#[test]
fn dependency_parser_preserves_conditions_versions_and_blockers() {
let deps = parse_dependencies(
">=dev-libs/glib-2.0 python? ( dev-lang/python ) !app-misc/old || ( a/b c/d )",
);
let by_atom = |atom: &str| {
deps.iter()
.find(|d| d.atom == atom)
.unwrap_or_else(|| panic!("missing {atom} in {deps:?}"))
};
assert_eq!(by_atom("dev-libs/glib").raw, ">=dev-libs/glib-2.0");
assert_eq!(
by_atom("dev-lang/python").condition.as_deref(),
Some("python?")
);
assert!(by_atom("app-misc/old").negative);
assert_eq!(by_atom("a/b").condition.as_deref(), Some("any-of"));
// self-atom normalization strips operators, slot and USE.
assert_eq!(
normalize_dep_atom(">=dev-lang/python-3.12:3.12[ssl]"),
"dev-lang/python"
);
}
#[test] #[test]
fn normalize_config_permissions_makes_read_only_queries_possible() { fn normalize_config_permissions_makes_read_only_queries_possible() {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;

View file

@ -89,19 +89,11 @@ fn stderr_tail(text: &str) -> String {
} }
} }
/// Whether the Flatpak client answers in the intended target. For an alternate /// Whether the Flatpak client answers in the target.
/// root the check runs inside the target chroot, never against the host. fn flatpak_available(exec: &Exec, root: &Path) -> bool {
pub(crate) fn flatpak_available(exec: &Exec, root: &Path) -> bool {
matches!(capture(exec, root, "flatpak", &["--version"]), Ok(o) if o.success) matches!(capture(exec, root, "flatpak", &["--version"]), Ok(o) if o.success)
} }
/// Snap operations act on the running daemon and cannot be redirected into an
/// alternate root. Availability must therefore refer to the running system;
/// pretending a target lane is usable would mutate the host.
fn snap_target_usable(exec: &Exec, root: &Path) -> bool {
crate::actions::is_host_root(root) && matches!(snap::status(exec), Ok(s) if s.usable())
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Search // Search
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@ -252,13 +244,8 @@ fn search_flatpak(exec: &Exec, root: &Path, query: &str, backend: Backend) -> So
} }
fn search_snap(exec: &Exec, root: &Path, query: &str, backend: Backend) -> SourceReport { fn search_snap(exec: &Exec, root: &Path, query: &str, backend: Backend) -> SourceReport {
if !crate::actions::is_host_root(root) { let usable = matches!(snap::status(exec), Ok(s) if s.usable());
return SourceReport::unsupported( if !usable {
backend,
"Snap cannot be queried for an alternate root; it acts on the running daemon",
);
}
if !snap_target_usable(exec, root) {
return SourceReport::unsupported(backend, "snapd is not installed or active"); return SourceReport::unsupported(backend, "snapd is not installed or active");
} }
let out = match capture(exec, root, "snap", &["find", query, "--color=never"]) { let out = match capture(exec, root, "snap", &["find", query, "--color=never"]) {
@ -467,14 +454,9 @@ fn inventory_flatpak(exec: &Exec, root: &Path, backend: Backend) -> SourceReport
SourceReport::ok(backend, "installed Flatpak applications", entries) SourceReport::ok(backend, "installed Flatpak applications", entries)
} }
fn inventory_snap(exec: &Exec, root: &Path, backend: Backend) -> SourceReport { fn inventory_snap(exec: &Exec, _root: &Path, backend: Backend) -> SourceReport {
if !crate::actions::is_host_root(root) { let usable = matches!(snap::status(exec), Ok(s) if s.usable());
return SourceReport::unsupported( if !usable {
backend,
"Snap cannot be inspected for an alternate root; it acts on the running daemon",
);
}
if !snap_target_usable(exec, root) {
return SourceReport::unsupported(backend, "snapd is not installed or active"); return SourceReport::unsupported(backend, "snapd is not installed or active");
} }
match snap::list(exec) { match snap::list(exec) {
@ -516,29 +498,23 @@ fn inventory_nix(root: &Path, backend: Backend) -> SourceReport {
let Some(store_paths) = nix::store_path_count(root) else { let Some(store_paths) = nix::store_path_count(root) else {
return SourceReport::unsupported(backend, "Nix is not installed"); return SourceReport::unsupported(backend, "Nix is not installed");
}; };
let inventory = nix::installed_packages(root); let profiles = nix::profiles(root);
let entries = inventory let entries = profiles
.packages
.into_iter() .into_iter()
.map(|p| { .map(|p| {
let mut entry = CatalogEntry::new(backend, p.path) let mut entry = CatalogEntry::new(backend, p.name)
.scope(p.profile) .scope("profile")
.installed(true); .installed(true);
if let Some(version) = p.version { if !p.target.is_empty() {
entry = entry.version(version); entry = entry.description(p.target);
} }
entry = entry.description(format!("Nix package `{}` ({})", p.name, p.store_path));
entry entry
}) })
.collect(); .collect();
let mut note = format!( let note = format!(
"active Nix profiles; {store_paths} additional store path(s) are realised \ "{store_paths} store path(s) realised but not installed profiles; \
dependencies, not installed packages" Nix is a per-project/developer lane, so store contents are not listed as packages"
); );
for additional in inventory.notes {
note.push_str("; ");
note.push_str(&additional);
}
SourceReport::ok(backend, note, entries) SourceReport::ok(backend, note, entries)
} }
@ -555,14 +531,8 @@ pub fn package_info(
filter: Option<Backend>, filter: Option<Backend>,
) -> PackageInfoReport { ) -> PackageInfoReport {
let lanes = selected_lanes(filter); let lanes = selected_lanes(filter);
// The filter is applied before any backend is queried, so a let installed = chooser::installed_copies(exec, root, package);
// source-constrained request never probes (or reports) another lane. let installed_portage = portage::installed_packages(root);
let installed = chooser::installed_copies_filtered(exec, root, package, filter);
let installed_portage = if filter.map(is_portage).unwrap_or(true) {
portage::installed_packages(root)
} else {
Vec::new()
};
let mut matches: Vec<PackageInfoMatch> = Vec::new(); let mut matches: Vec<PackageInfoMatch> = Vec::new();
let mut notes: Vec<String> = Vec::new(); let mut notes: Vec<String> = Vec::new();
@ -735,9 +705,8 @@ fn split_depend(value: &str) -> Vec<String> {
/// Which installed package owns a file path (Portage). /// Which installed package owns a file path (Portage).
pub fn package_owners(exec: &Exec, root: &Path, path: &str) -> Result<String> { pub fn package_owners(exec: &Exec, root: &Path, path: &str) -> Result<String> {
// Prefer `qfile` (portage-utils), then `equery belongs` (gentoolkit). The // Prefer `qfile` (portage-utils), then `equery belongs` (gentoolkit).
// tool must be present in the intended target, not merely on the host. if crate::exec::find_in_path("qfile").is_some() {
if crate::exec::tool_in_target(root, "qfile") {
let out = capture(exec, root, "qfile", &[path])?; let out = capture(exec, root, "qfile", &[path])?;
if !out.success { if !out.success {
return Ok(format!("no installed package owns {path}")); return Ok(format!("no installed package owns {path}"));
@ -747,7 +716,7 @@ pub fn package_owners(exec: &Exec, root: &Path, path: &str) -> Result<String> {
out.stdout_lossy().trim() out.stdout_lossy().trim()
)); ));
} }
if crate::exec::tool_in_target(root, "equery") { if crate::exec::find_in_path("equery").is_some() {
let out = capture(exec, root, "equery", &["belongs", path])?; let out = capture(exec, root, "equery", &["belongs", path])?;
if !out.success { if !out.success {
return Ok(format!("no installed package owns {path}")); return Ok(format!("no installed package owns {path}"));
@ -765,142 +734,53 @@ pub fn package_owners(exec: &Exec, root: &Path, path: &str) -> Result<String> {
)) ))
} }
/// The declared dependency fields of an installed VDB record.
fn declared_dependencies(record: &portage::InstalledPortage) -> Vec<portage::DeclaredDependency> {
let mut deps = Vec::new();
for text in [&record.depend, &record.rdepend, &record.bdepend]
.into_iter()
.flatten()
{
deps.extend(portage::parse_dependencies(text));
}
deps
}
/// Whether `atom` (a `category/name`) matches a requested package (bare name,
/// full atom, or atom-with-version).
fn atom_matches(atom: &str, package: &str) -> bool {
let wanted = portage::normalize_dep_atom(package);
atom == wanted
|| wanted.ends_with(&format!("/{package}"))
|| atom.ends_with(&format!("/{package}"))
}
/// Forward or reverse dependencies of an installed Portage package. /// Forward or reverse dependencies of an installed Portage package.
///
/// Dependencies come from the authoritative installed metadata (the VDB
/// `DEPEND`/`RDEPEND`/`BDEPEND` fields), so already-satisfied dependencies are
/// included and conditional/versioned dependencies keep their context. An
/// install plan from `emerge --pretend` is deliberately not used: it describes
/// pending merges, not the full dependency graph. For a package that is not
/// installed, `qdepends` (portage-utils) is used when present, else the query is
/// refused with a clear limitation rather than guessing.
pub fn package_dependencies( pub fn package_dependencies(
exec: &Exec, exec: &Exec,
root: &Path, root: &Path,
package: &str, package: &str,
reverse: bool, reverse: bool,
) -> Result<String> { ) -> Result<String> {
let installed = portage::installed_packages(root);
let installed_atoms: std::collections::BTreeSet<String> =
installed.iter().map(|p| p.atom.clone()).collect();
let self_atom = installed
.iter()
.find(|p| atom_matches(&p.atom, package))
.map(|p| p.atom.clone());
let mut lines: Vec<String> = Vec::new();
if reverse { if reverse {
for record in &installed { if crate::exec::find_in_path("equery").is_none() {
for dep in declared_dependencies(record) {
if atom_matches(&dep.atom, package) && Some(&dep.atom) != self_atom.as_ref() {
let conditional = dep
.condition
.as_deref()
.map(|c| format!("[{c}] "))
.unwrap_or_default();
lines.push(format!("{conditional}{} (from {})", dep.raw, record.atom));
}
}
}
lines.sort();
lines.dedup();
if lines.is_empty() {
return Ok(format!(
"no installed package depends on {package}\n (installed metadata is authoritative \
for reverse dependencies; nothing references it)"
));
}
return Ok(format!(
"installed packages depending on {package}:\n {}",
lines.join("\n ")
));
}
// Forward: prefer the installed metadata; fall back to the tree via
// qdepends only when the package is not installed.
let deps: Vec<(String, Option<String>, bool)> =
if let Some(record) = installed.iter().find(|p| atom_matches(&p.atom, package)) {
declared_dependencies(record)
.into_iter()
.filter(|d| Some(&d.atom) != self_atom.as_ref())
.map(|d| (d.raw, d.condition, d.negative))
.collect()
} else if crate::exec::tool_in_target(root, "qdepends") {
let out = capture(exec, root, "qdepends", &["-Q", "--", package])?;
if !out.success {
return Err(ExecError::operation(
"sys",
"dependencies",
format!(
"qdepends could not resolve dependencies for {package}: {}",
stderr_tail(&out.stderr_lossy())
),
));
}
portage::parse_dependencies(&out.stdout_lossy())
.into_iter()
.map(|d| (d.raw, d.condition, d.negative))
.collect()
} else {
return Err(ExecError::operation( return Err(ExecError::operation(
"sys", "sys",
"dependencies", "reverse dependencies",
format!( "reverse-dependency inspection requires app-portage/gentoolkit (equery depends)",
"{package} is not installed, and no dependency inspection tool is available; \
install app-portage/portage-utils (qdepends) or inspect it through Portage"
),
)); ));
}; }
let out = capture(exec, root, "equery", &["depends", package])?;
if !out.success {
return Ok(format!("no installed package depends on {package}"));
}
return Ok(out.stdout_lossy().trim().to_string());
}
if deps.is_empty() { match capture(
return Ok(format!( exec,
"{package} has no declared dependencies in the installed metadata" root,
)); "emerge",
&["--pretend", "--quiet", "--color=n", "--", package],
) {
Ok(out) if out.success => {
let plan = phoebus_core::effects::parse_emerge_pretend(&out.stdout_lossy());
let deps: Vec<String> = plan.effects.iter().map(|e| e.target.clone()).collect();
if deps.is_empty() {
Ok(format!("{package} has no resolved dependencies"))
} else {
Ok(format!("{package} depends on:\n {}", deps.join("\n ")))
}
}
Ok(out) => Ok(format!(
"could not resolve dependencies for {package}: {}",
stderr_tail(&out.stderr_lossy())
)),
Err(e) => Err(ExecError::operation(
"sys",
"dependencies",
format!("could not resolve dependencies for {package}: {e}"),
)),
} }
let mut rendered = Vec::new();
for (raw, condition, negative) in deps {
let atom = portage::normalize_dep_atom(&raw);
let satisfied = if negative {
"blocker"
} else if installed_atoms.contains(&atom) {
"installed"
} else {
"not installed"
};
let conditional = condition
.as_deref()
.map(|c| format!("[{c}] "))
.unwrap_or_default();
rendered.push(format!("{conditional}{raw} ({satisfied})"));
}
rendered.sort();
rendered.dedup();
Ok(format!(
"{package} declares {} dependency token(s):\n {}",
rendered.len(),
rendered.join("\n ")
))
} }
/// Remove packages no longer required by any installed package (Portage). /// Remove packages no longer required by any installed package (Portage).
@ -945,11 +825,6 @@ pub fn depclean(exec: &Exec, root: &Path) -> Result<String> {
/// Remove unreferenced package caches / store paths. Never removes an /// Remove unreferenced package caches / store paths. Never removes an
/// installed package. /// installed package.
///
/// Every cleaner's outcome is preserved: a cleaner that ran and failed makes
/// the whole action fail (with the partial successes still reported), and a
/// missing cleaner is distinguished from one that ran and found nothing. A
/// cleanup that could not run at all is a failure, not a silent success.
pub fn clean_cache(exec: &Exec, root: &Path, filter: Option<Backend>) -> Result<String> { pub fn clean_cache(exec: &Exec, root: &Path, filter: Option<Backend>) -> Result<String> {
let lanes: Vec<Backend> = match filter { let lanes: Vec<Backend> = match filter {
Some(backend) => vec![backend], Some(backend) => vec![backend],
@ -957,307 +832,139 @@ pub fn clean_cache(exec: &Exec, root: &Path, filter: Option<Backend>) -> Result<
}; };
let mut report = String::new(); let mut report = String::new();
report.push_str("cache cleanup (installed packages are never removed)\n"); report.push_str("cache cleanup (installed packages are never removed)\n");
let mut completed = 0usize;
let mut failed = false;
for lane in lanes { for lane in lanes {
if lane.is_portage() { match lane {
let mut attempted = false; Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
for (cleaner, _, destructive_args) in crate::actions::portage_cleaners(root) { report.push_str(&clean_portage_cache(exec, root));
attempted = true; }
match run_mut( Backend::Nix => {
exec, if !nix::installed(root) {
root, report.push_str(" [nix] unavailable: Nix is not installed\n");
cleaner, } else {
&destructive_args nix::gc(exec, root)?;
.iter() report
.map(|s| s.as_str()) .push_str(" [nix] unreferenced store paths collected (nix-store --gc)\n");
.collect::<Vec<_>>(),
) {
Ok(()) => {
completed += 1;
report.push_str(&format!(" [portage] {cleaner} completed\n"));
}
Err(e) => {
failed = true;
report.push_str(&format!(" [portage] {cleaner} failed: {e}\n"));
}
} }
} }
if !attempted { other => report.push_str(&format!(
report.push_str( " [{}] unsupported: this lane has no package cache to clean\n",
" [portage] unavailable: no cleaner in the target (install \ other.as_str()
app-portage/gentoolkit for eclean-dist / eclean-pkg)\n", )),
);
}
} else if lane == Backend::Nix {
if !nix::installed(root) {
report.push_str(" [nix] unavailable: Nix is not installed\n");
} else {
match nix::gc(exec, root) {
Ok(()) => {
completed += 1;
report.push_str(
" [nix] unreferenced store paths collected (nix-store --gc)\n",
);
}
Err(e) => {
failed = true;
report.push_str(&format!(" [nix] cleanup failed: {e}\n"));
}
}
}
} else {
return Err(ExecError::operation(
"sys",
"clean cache",
format!(
"the {} lane has no package cache to clean; refusing",
lane.as_str()
),
));
} }
} }
if failed {
return Err(ExecError::operation("sys", "clean cache", report));
}
if completed == 0 {
return Err(ExecError::operation(
"sys",
"clean cache",
format!("{report}no cleaner ran"),
));
}
Ok(report) Ok(report)
} }
fn clean_portage_cache(exec: &Exec, root: &Path) -> String {
let mut out = String::new();
let mut cleaned = false;
if crate::exec::find_in_path("eclean-dist").is_some() {
match run_mut(exec, root, "eclean-dist", &["-d"]) {
Ok(()) => {
out.push_str(" [portage] distfiles cleaned (eclean-dist -d)\n");
cleaned = true;
}
Err(e) => out.push_str(&format!(" [portage] distfile cleanup failed: {e}\n")),
}
}
if crate::exec::find_in_path("eclean-pkg").is_some() {
match run_mut(exec, root, "eclean-pkg", &["-d"]) {
Ok(()) => {
out.push_str(" [portage] binary package cache cleaned (eclean-pkg -d)\n");
cleaned = true;
}
Err(e) => out.push_str(&format!(" [portage] package cache cleanup failed: {e}\n")),
}
}
if !cleaned {
out.push_str(
" [portage] unsupported: install app-portage/gentoolkit (eclean-dist / eclean-pkg)\n",
);
}
out
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Updates // Updates
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// Check for updates across the supported lanes, optionally restricted to one. /// Check for updates across the supported lanes, optionally restricted to one.
pub fn check_updates(exec: &Exec, root: &Path, filter: Option<Backend>) -> UnifiedUpdateOverview { pub fn check_updates(exec: &Exec, root: &Path, filter: Option<Backend>) -> UnifiedUpdateOverview {
// The filter is applied before any backend is queried, not merely to the let mut overview = crate::update::check_unified_updates(exec, root);
// displayed results. if let Some(filter) = filter {
crate::update::check_unified_updates_filtered(exec, root, filter) overview.sources.retain(|s| lane_matches(s.backend, filter));
}
/// The exact Flatpak applications with an available update. Each is updated by
/// ref so execution can never become an unrestricted update-all.
fn flatpak_update_ids(exec: &Exec, root: &Path) -> Result<Vec<String>> {
let out = capture(
exec,
root,
"flatpak",
&[
"remote-ls",
"--updates",
"--columns=application,version,branch",
],
)?;
if !out.success {
return Err(ExecError::operation(
"sys",
"apply flatpak updates",
format!(
"flatpak remote-ls failed: {}",
stderr_tail(&out.stderr_lossy())
),
));
} }
let mut ids = Vec::new(); overview
for line in out.stdout_lossy().lines() {
if let Some(id) = line.split_whitespace().next() {
if !id.is_empty() {
ids.push(id.to_string());
}
}
}
ids.sort();
ids.dedup();
Ok(ids)
}
/// The exact snaps with an available update.
fn snap_update_names(exec: &Exec) -> Result<Vec<String>> {
let out = exec.runner.execute(
&CommandSpec::new("sys", "apply snap updates", "snap").args(["refresh", "--list"]),
)?;
if !out.success {
return Err(ExecError::operation(
"sys",
"apply snap updates",
format!(
"snap refresh --list failed: {}",
stderr_tail(&out.stderr_lossy())
),
));
}
let mut names = Vec::new();
for line in out.stdout_lossy().lines().skip(1) {
if let Some(name) = line.split_whitespace().next() {
if !name.is_empty() {
names.push(name.to_string());
}
}
}
names.sort();
names.dedup();
Ok(names)
} }
/// Apply updates across the supported lanes and report a truthful per-source /// Apply updates across the supported lanes and report a truthful per-source
/// outcome. Each per-source update is constrained to the exact identities /// outcome. Sources that require manual or project-specific updates are
/// resolved immediately before execution; a source that ran and failed is /// explained, never reported as updated. If any attempted source fails, the
/// reported as failed (with partial success preserved), and the whole action /// whole action fails with the per-source report.
/// then fails. Sources with no safe system-level transaction are refused.
pub fn apply_updates(exec: &Exec, root: &Path, filter: Option<Backend>) -> Result<String> { pub fn apply_updates(exec: &Exec, root: &Path, filter: Option<Backend>) -> Result<String> {
let lanes: Vec<Backend> = match filter { let lanes: Vec<Backend> = match filter {
Some(backend) => vec![backend], Some(backend) => vec![backend],
None => vec![Backend::PortageSource, Backend::Flatpak, Backend::Snap], None => all_lanes(),
}; };
let mut report = String::new(); let mut report = String::new();
report.push_str("update application (per-source outcome)\n"); report.push_str("update application (per-source outcome)\n");
let mut failed = false; let mut failed = false;
let mut completed = 0usize;
for lane in lanes { for lane in lanes {
if lane.is_portage() { match lane {
match crate::actions::portage_world_update(exec, root) { Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
Ok(()) => { match crate::actions::portage_world_update(exec, root) {
completed += 1; Ok(()) => report.push_str(" [portage] updated (emerge -uDN @world)\n"),
report.push_str(" [portage] updated (emerge -uDN @world)\n"); Err(e) => {
} failed = true;
Err(e) => { report.push_str(&format!(" [portage] failed: {e}\n"));
failed = true; }
report.push_str(&format!(" [portage] failed: {e}\n"));
} }
} }
} else if lane == Backend::Flatpak { Backend::Flatpak => {
if !flatpak_available(exec, root) { if !flatpak_available(exec, root) {
if filter.is_some() {
failed = true;
report.push_str(
" [flatpak] failed: the Flatpak client is not available in the target\n",
);
} else {
report.push_str(" [flatpak] unavailable: the Flatpak client is not present\n"); report.push_str(" [flatpak] unavailable: the Flatpak client is not present\n");
}
continue;
}
match flatpak_update_ids(exec, root) {
Ok(ids) if ids.is_empty() => {
completed += 1;
report.push_str(" [flatpak] no updates available\n");
}
Ok(ids) => {
let mut lane_failed = false;
for id in &ids {
match run_mut(exec, root, "flatpak", &["update", "-y", "--", id]) {
Ok(()) => {}
Err(e) => {
lane_failed = true;
report.push_str(&format!(" [flatpak] {id} failed: {e}\n"));
}
}
}
if lane_failed {
failed = true;
} else {
completed += 1;
report.push_str(&format!(
" [flatpak] updated {} reviewed application(s): {}\n",
ids.len(),
ids.join(", ")
));
}
}
Err(e) => {
failed = true;
report.push_str(&format!(" [flatpak] failed: {e}\n"));
}
}
} else if lane == Backend::Snap {
if !crate::actions::is_host_root(root) {
failed = true;
report
.push_str(" [snap] refused: Snap cannot be redirected to an alternate root\n");
continue;
}
let usable = matches!(snap::status(exec), Ok(s) if s.usable());
if !usable {
if filter.is_some() {
failed = true;
report.push_str(" [snap] failed: snapd is not installed or active\n");
} else { } else {
report.push_str(" [snap] unavailable: snapd is not installed or active\n"); match run_mut(exec, root, "flatpak", &["update", "-y"]) {
} Ok(()) => report.push_str(" [flatpak] updated (flatpak update -y)\n"),
continue; Err(e) => {
} failed = true;
match snap_update_names(exec) { report.push_str(&format!(" [flatpak] failed: {e}\n"));
Ok(names) if names.is_empty() => {
completed += 1;
report.push_str(" [snap] no updates available\n");
}
Ok(names) => {
let mut lane_failed = false;
for name in &names {
match snap::refresh(exec, Some(name)) {
Ok(_) => {}
Err(e) => {
lane_failed = true;
report.push_str(&format!(" [snap] {name} failed: {e}\n"));
}
} }
} }
if lane_failed {
failed = true;
} else {
completed += 1;
report.push_str(&format!(
" [snap] refreshed {} reviewed snap(s): {}\n",
names.len(),
names.join(", ")
));
}
}
Err(e) => {
failed = true;
report.push_str(&format!(" [snap] failed: {e}\n"));
} }
} }
} else if filter.is_some() { Backend::Snap => {
// An explicit request for a lane with no safe system-level update let usable = matches!(snap::status(exec), Ok(s) if s.usable());
// transaction is refused, not silently reported as "updated". if !usable {
return Err(ExecError::operation( report.push_str(" [snap] unavailable: snapd is not installed or active\n");
"sys", } else {
"apply updates", match snap::refresh(exec, None) {
format!( Ok(_) => report.push_str(" [snap] refreshed (snap refresh)\n"),
"{} updates cannot be applied safely by `sys` from the system; {}", Err(e) => {
lane.as_str(), failed = true;
crate::actions::update_limitation(lane) report.push_str(&format!(" [snap] failed: {e}\n"));
), }
)); }
} else { }
report.push_str(&format!( }
" [{}] not applied: {}\n", Backend::AppImage => report.push_str(
lane.as_str(), " [appimage] manual: managed AppImages have no update repository; \
crate::actions::update_limitation(lane) re-acquire with a pinned URL + SHA-256 (appimage_update)\n",
)); ),
Backend::Nix => report.push_str(
" [nix] project-specific: Nix packages are declarative/pinned; \
update them in their project or profile, not from the system\n",
),
Backend::CustomEbuild => report.push_str(
" [custom-ebuild] project-specific: rebuild a staged ebuild through Portage\n",
),
} }
} }
if failed { if failed {
return Err(ExecError::operation("sys", "apply updates", report)); return Err(ExecError::operation("sys", "apply updates", report));
} }
if completed == 0 {
return Err(ExecError::operation(
"sys",
"apply updates",
format!("{report}no source was updated"),
));
}
Ok(report) Ok(report)
} }
@ -1477,90 +1184,23 @@ mod tests {
assert_eq!(runner2.recorded().len(), 2); assert_eq!(runner2.recorded().len(), 2);
} }
fn install_fake_tool(root: &Path, name: &str) {
use std::os::unix::fs::PermissionsExt;
let bin = root.join("usr/bin");
std::fs::create_dir_all(&bin).unwrap();
let tool = bin.join(name);
std::fs::write(&tool, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
}
#[test] #[test]
fn clean_cache_without_a_cleaner_is_a_failure_not_a_silent_success() { fn clean_cache_reports_unsupported_without_a_cleaner() {
// A temp dir with neither eclean-dist nor eclean-pkg in the target. // A temp dir with neither eclean-dist nor eclean-pkg on PATH.
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
let exec = make_exec(runner); let exec = make_exec(runner);
let err = let out = clean_cache(&exec, Path::new(&exec.root), Some(Backend::PortageSource)).unwrap();
clean_cache(&exec, Path::new(&exec.root), Some(Backend::PortageSource)).unwrap_err(); assert!(out.contains("installed packages are never removed"));
let text = err.to_string(); assert!(out.contains("unsupported") || out.contains("cleaned"));
assert!(text.contains("no cleaner ran"), "{text}");
// The unavailable tool is named distinctly from a failed tool.
assert!(text.contains("unavailable"), "{text}");
} }
#[test] #[test]
fn clean_cache_propagates_a_failed_cleaner_and_preserves_partial_success() { fn apply_updates_reports_manual_and_project_lanes_without_claiming_success() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let root = Path::new(&exec.root);
install_fake_tool(root, "eclean-dist");
install_fake_tool(root, "eclean-pkg");
// The first cleaner runs; the second fails. Execution is rooted in the
// target (chroot), so both are the `chroot` wrapper; fail the second.
let chroot_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
struct FailSecond(std::sync::Arc<std::sync::atomic::AtomicUsize>);
impl crate::command::ProcessRunner for FailSecond {
fn execute(&self, _spec: &crate::command::CommandSpec) -> Result<CommandOutput> {
let n = self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if n == 0 {
Ok(CommandOutput {
status: 0,
success: true,
stdout: Vec::new(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
})
} else {
Ok(CommandOutput {
status: 1,
success: false,
stdout: Vec::new(),
stderr: b"eclean boom".to_vec(),
duration: std::time::Duration::from_millis(1),
})
}
}
}
let logger_path = tempfile::tempdir().unwrap().keep();
let logger = crate::log::Logger::open(
logger_path.join("l.log"),
phoebus_core::Redactor::new(),
false,
);
let exec2 = Exec::new(
Box::new(FailSecond(chroot_calls)),
logger,
false,
root,
logger_path,
);
let err = clean_cache(&exec2, root, Some(Backend::PortageSource)).unwrap_err();
let text = err.to_string();
assert!(text.contains("eclean-dist completed"), "{text}");
assert!(text.contains("eclean-pkg failed"), "{text}");
// The runner was consulted, and no host command was issued.
assert!(runner.recorded().is_empty());
}
#[test]
fn apply_updates_refuses_a_lane_without_a_safe_transaction() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
let exec = make_exec(runner); let exec = make_exec(runner);
let err = apply_updates(&exec, Path::new(&exec.root), Some(Backend::AppImage)).unwrap_err(); let out = apply_updates(&exec, Path::new(&exec.root), Some(Backend::AppImage)).unwrap();
let text = err.to_string(); assert!(out.contains("manual"));
assert!(text.contains("cannot be applied safely"), "{text}"); assert!(!out.contains("updated"));
assert!(text.contains("pinned URL"), "{text}");
} }
#[test] #[test]
@ -1573,111 +1213,6 @@ mod tests {
assert!(err.to_string().contains("[portage] failed")); assert!(err.to_string().contains("[portage] failed"));
} }
#[test]
fn flatpak_update_plan_is_refused_when_the_target_has_no_client() {
let runner = RecordingRunner::new();
runner.fail("chroot", "flatpak: not found");
let exec = make_exec(runner);
let root = Path::new(&exec.root);
let plan = crate::actions::resolve_effects(
&exec,
&phoebus_core::action::SystemAction::ApplyUpdates {
backend: Some(Backend::Flatpak),
},
root,
);
// No flatpak in the target, so the plan is refused rather than silently
// reporting success.
assert!(plan.is_err());
}
#[test]
fn flatpak_update_effects_bind_exact_identities_and_versions() {
use crate::command::{CommandOutput, CommandSpec, ProcessRunner};
struct Fp;
impl ProcessRunner for Fp {
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
let ok = |s: &str| CommandOutput {
status: 0,
success: true,
stdout: s.as_bytes().to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
};
let flatpak = spec.args.iter().any(|a| a == "flatpak");
if flatpak && spec.args.iter().any(|a| a == "--version") {
return Ok(ok("Flatpak 1.18\n"));
}
if flatpak && spec.args.iter().any(|a| a == "remote-ls") {
return Ok(ok(
"org.mozilla.firefox 129 stable\norg.gnome.Calc 46 stable\n",
));
}
if flatpak && spec.args.iter().any(|a| a == "list") {
return Ok(ok("org.mozilla.firefox 128\norg.gnome.Calc 45\n"));
}
Ok(ok(""))
}
}
let path = tempfile::tempdir().unwrap().keep();
let logger =
crate::log::Logger::open(path.join("l.log"), phoebus_core::Redactor::new(), false);
let exec = Exec::new(Box::new(Fp), logger, false, path.join("root"), path);
let plan = crate::actions::resolve_effects(
&exec,
&phoebus_core::action::SystemAction::ApplyUpdates {
backend: Some(Backend::Flatpak),
},
&exec.root,
)
.unwrap();
assert!(plan.established);
assert!(
plan.effects
.iter()
.any(|e| e.target == "org.mozilla.firefox-129"
&& e.previous.as_deref() == Some("128"))
);
assert!(plan
.effects
.iter()
.any(|e| e.target == "org.gnome.Calc-46" && e.previous.as_deref() == Some("45")));
}
#[test]
fn alternate_root_flatpak_search_is_chrooted_and_never_host() {
let runner = RecordingRunner::new();
runner.set_response("chroot", ok("org.mozilla.firefox\t128\tFirefox\n"));
let exec = make_exec(runner.clone());
let root = Path::new(&exec.root);
install_fake_tool(root, "flatpak");
let report = search(&exec, root, "firefox", Some(Backend::Flatpak));
assert!(report.sources[0].supported, "{:?}", report.sources[0]);
// No host flatpak/snap process may be invoked for an alternate root.
assert!(
!runner
.recorded()
.iter()
.any(|s| s.program == "flatpak" || s.program == "snap"),
"{:?}",
runner.programs()
);
}
#[test]
fn apply_updates_never_runs_host_snap_for_an_alternate_root() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let err = apply_updates(&exec, Path::new(&exec.root), Some(Backend::Snap)).unwrap_err();
assert!(err.to_string().contains("alternate root"), "{err}");
// Crucially, no host `snap` command was attempted.
assert!(
!runner.recorded().iter().any(|s| s.program == "snap"),
"alternate-root snap must not touch the host: {:?}",
runner.programs()
);
}
#[test] #[test]
fn parse_flatpak_lines_handles_tabs_and_spaces() { fn parse_flatpak_lines_handles_tabs_and_spaces() {
let rows = let rows =
@ -1697,59 +1232,15 @@ mod tests {
} }
#[test] #[test]
fn package_dependencies_uses_installed_metadata_not_an_install_plan() { fn package_dependencies_reports_forward_deps() {
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
runner.set_response(
"emerge",
ok("Calculating dependencies... done!\n[ebuild N ] app-editors/vim-core-9.1.0\n\nTotal: 1 package\n"),
);
let exec = make_exec(runner); let exec = make_exec(runner);
let root = Path::new(&exec.root); let out = package_dependencies(&exec, Path::new("/"), "vim", false).unwrap();
// `vim` depends on an already-installed runtime library, a conditional assert!(out.contains("app-editors/vim-core-9.1.0"), "{out}");
// dependency and a blocker; `vim-core` is already installed.
for (atom, version) in [
("app-editors/vim", "9.1.0"),
("app-editors/vim-core", "9.1.0"),
] {
let dir = root.join(format!("var/db/pkg/{atom}-{version}"));
std::fs::create_dir_all(&dir).unwrap();
}
std::fs::write(
root.join("var/db/pkg/app-editors/vim-9.1.0/RDEPEND"),
"app-editors/vim-core python? ( dev-lang/python ) !app-editors/vim-minimal",
)
.unwrap();
let out = package_dependencies(&exec, root, "app-editors/vim", false).unwrap();
assert!(out.contains("app-editors/vim-core"), "{out}");
assert!(
out.contains("(installed)"),
"satisfied deps included: {out}"
);
assert!(out.contains("dev-lang/python"), "{out}");
assert!(
out.contains("python?"),
"conditional context preserved: {out}"
);
assert!(out.contains("blocker"), "{out}");
// The requested package is never reported as its own dependency.
assert!(
!out.contains("app-editors/vim (") && !out.contains("app-editors/vim-9.1.0"),
"{out}"
);
}
#[test]
fn package_dependencies_reverse_finds_installed_dependants() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let root = Path::new(&exec.root);
let dir = root.join("var/db/pkg/app-misc/tool-1.0");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("RDEPEND"), ">=dev-libs/glib-2.0").unwrap();
let out = package_dependencies(&exec, root, "dev-libs/glib", true).unwrap();
assert!(out.contains("app-misc/tool"), "{out}");
// A genuinely empty reverse set is distinct from a failed query.
let empty = package_dependencies(&exec, root, "dev-libs/nothing", true).unwrap();
assert!(empty.contains("no installed package depends on"), "{empty}");
} }
#[test] #[test]

View file

@ -166,204 +166,147 @@ use phoebus_core::update::{PackageUpdateItem, SourceUpdateOverview, UnifiedUpdat
/// Check updates across all supported package sources (Portage, Flatpak, Snap, AppImage, Nix) /// Check updates across all supported package sources (Portage, Flatpak, Snap, AppImage, Nix)
/// and report a unified, truthful overview. /// and report a unified, truthful overview.
pub fn check_unified_updates(exec: &Exec, root: &Path) -> UnifiedUpdateOverview { pub fn check_unified_updates(exec: &Exec, root: &Path) -> UnifiedUpdateOverview {
check_unified_updates_filtered(exec, root, None)
}
/// Whether a lane is covered by an optional source filter.
fn lane_selected(filter: Option<Backend>, lane: Backend) -> bool {
match filter {
Some(f) => f == lane || (f.is_portage() && lane.is_portage()),
None => true,
}
}
/// Like [`check_unified_updates`], but a lane filter prevents querying any
/// other backend at all, so a constrained check never probes a foreign lane.
pub fn check_unified_updates_filtered(
exec: &Exec,
root: &Path,
filter: Option<Backend>,
) -> UnifiedUpdateOverview {
let mut sources = Vec::new(); let mut sources = Vec::new();
// 1. Portage. The check runs against the intended target: directly for the // 1. Portage
// running root, or inside the target chroot for an alternate root. let mut portage_items = Vec::new();
if lane_selected(filter, Backend::PortageSource) { let portage_res = exec.runner.execute(
let mut portage_items = Vec::new(); &crate::command::CommandSpec::new("sys", "check portage updates", "emerge").args([
let portage_args: Vec<String> = [
"--pretend", "--pretend",
"--update", "--update",
"--deep", "--deep",
"--newuse", "--newuse",
"--color=n", "--color=n",
"@world", "@world",
] ]),
.iter() );
.map(|s| s.to_string()) let mut portage_note = "native OS packages".to_string();
.collect(); if let Ok(res) = portage_res {
let portage_res = exec.runner.execute(&crate::actions::target_spec( if res.success {
root, let plan = phoebus_core::effects::parse_emerge_pretend(&res.stdout_lossy());
"sys", for effect in plan.effects {
"check portage updates", if effect.kind == phoebus_core::effects::EffectKind::Upgrade
"emerge", || effect.kind == phoebus_core::effects::EffectKind::New
&portage_args, {
)); portage_items.push(PackageUpdateItem {
let mut portage_note = "native OS packages".to_string(); name: effect.target.clone(),
if let Ok(res) = portage_res { current_version: effect.previous.clone(),
new_version: effect.target,
source: "Portage @world".into(),
});
}
}
} else {
portage_note = "emerge check failed or offline".into();
}
}
sources.push(SourceUpdateOverview {
backend: Backend::PortageSource,
updates: portage_items,
supported: true,
note: portage_note,
});
// 2. Flatpak
let mut flatpak_items = Vec::new();
let flatpak_supported = crate::exec::find_in_path("flatpak").is_some();
let mut flatpak_note = "sandboxed desktop applications".to_string();
if flatpak_supported {
let fp_res =
exec.runner.execute(
&crate::command::CommandSpec::new("sys", "check flatpak updates", "flatpak")
.args(["remote-ls", "--updates", "--columns=application,version"]),
);
if let Ok(res) = fp_res {
if res.success { if res.success {
let plan = phoebus_core::effects::parse_emerge_pretend(&res.stdout_lossy()); for line in res.stdout_lossy().lines() {
for effect in plan.effects { let mut parts = line.split_whitespace();
if effect.kind == phoebus_core::effects::EffectKind::Upgrade if let (Some(id), Some(ver)) = (parts.next(), parts.next()) {
|| effect.kind == phoebus_core::effects::EffectKind::New flatpak_items.push(PackageUpdateItem {
{ name: id.to_string(),
portage_items.push(PackageUpdateItem { current_version: None,
name: effect.target.clone(), new_version: ver.to_string(),
current_version: effect.previous.clone(), source: "flathub".into(),
new_version: effect.target,
source: "Portage @world".into(),
}); });
} }
} }
} else { } else {
portage_note = "emerge check failed or offline".into(); flatpak_note = "flatpak remote check failed or offline".into();
} }
} }
sources.push(SourceUpdateOverview {
backend: Backend::PortageSource,
updates: portage_items,
supported: true,
note: portage_note,
});
} }
sources.push(SourceUpdateOverview {
// 2. Flatpak. Availability and the query refer to the target, so an backend: Backend::Flatpak,
// alternate-root check never consults a host Flatpak installation. updates: flatpak_items,
if lane_selected(filter, Backend::Flatpak) { supported: flatpak_supported,
let mut flatpak_items = Vec::new(); note: if flatpak_supported {
let flatpak_supported = crate::exec::tool_in_target(root, "flatpak"); flatpak_note
let mut flatpak_note = "sandboxed desktop applications".to_string();
if flatpak_supported {
let fp_args: Vec<String> = [
"remote-ls",
"--updates",
"--columns=application,version,branch",
]
.iter()
.map(|s| s.to_string())
.collect();
let fp_res = exec.runner.execute(&crate::actions::target_spec(
root,
"sys",
"check flatpak updates",
"flatpak",
&fp_args,
));
if let Ok(res) = fp_res {
if res.success {
for line in res.stdout_lossy().lines() {
let mut parts = line.split_whitespace();
if let (Some(id), Some(ver)) = (parts.next(), parts.next()) {
flatpak_items.push(PackageUpdateItem {
name: id.to_string(),
current_version: None,
new_version: ver.to_string(),
source: "flathub".into(),
});
}
}
} else {
flatpak_note = "flatpak remote check failed or offline".into();
}
}
}
sources.push(SourceUpdateOverview {
backend: Backend::Flatpak,
updates: flatpak_items,
supported: flatpak_supported,
note: if flatpak_supported {
flatpak_note
} else {
"flatpak is not installed".into()
},
});
}
// 3. Snap. Snap acts on the running daemon; an alternate-root check must
// not consult (or claim) the host's snaps.
if lane_selected(filter, Backend::Snap) {
let mut snap_items = Vec::new();
let snap_status = if root == Path::new("/") {
crate::snap::status(exec)
} else { } else {
Ok(crate::snap::SnapdStatus { "flatpak is not installed".into()
client_present: false, },
daemon_ready: false, });
confinement: crate::snap::Confinement::None,
}) // 3. Snap
}; let mut snap_items = Vec::new();
let snap_supported = matches!(snap_status, Ok(ref s) if s.usable()); let snap_status = crate::snap::status(exec);
let snap_note = "snapd automatic refresh lane".to_string(); let snap_supported = matches!(snap_status, Ok(ref s) if s.usable());
if snap_supported { let snap_note = "snapd automatic refresh lane".to_string();
let snap_res = exec.runner.execute( if snap_supported {
&crate::command::CommandSpec::new("sys", "check snap updates", "snap") let snap_res = exec.runner.execute(
.args(["refresh", "--list"]), &crate::command::CommandSpec::new("sys", "check snap updates", "snap")
); .args(["refresh", "--list"]),
if let Ok(res) = snap_res { );
if res.success { if let Ok(res) = snap_res {
for line in res.stdout_lossy().lines().skip(1) { if res.success {
let mut parts = line.split_whitespace(); for line in res.stdout_lossy().lines().skip(1) {
if let (Some(name), Some(ver)) = (parts.next(), parts.next()) { let mut parts = line.split_whitespace();
snap_items.push(PackageUpdateItem { if let (Some(name), Some(ver)) = (parts.next(), parts.next()) {
name: name.to_string(), snap_items.push(PackageUpdateItem {
current_version: None, name: name.to_string(),
new_version: ver.to_string(), current_version: None,
source: "Snap Store".into(), new_version: ver.to_string(),
}); source: "Snap Store".into(),
} });
} }
} }
} }
} }
sources.push(SourceUpdateOverview {
backend: Backend::Snap,
updates: snap_items,
supported: snap_supported,
note: if snap_supported {
snap_note
} else {
"snapd is not installed or active".into()
},
});
} }
sources.push(SourceUpdateOverview {
backend: Backend::Snap,
updates: snap_items,
supported: snap_supported,
note: if snap_supported {
snap_note
} else {
"snapd is not installed or active".into()
},
});
// 4. AppImage // 4. AppImage
if lane_selected(filter, Backend::AppImage) { let appimages = crate::appimage::list(root).unwrap_or_default();
let appimages = crate::appimage::list(root).unwrap_or_default(); sources.push(SourceUpdateOverview {
sources.push(SourceUpdateOverview { backend: Backend::AppImage,
backend: Backend::AppImage, updates: Vec::new(),
updates: Vec::new(), supported: false,
supported: false, note: format!(
note: format!( "{} managed AppImage(s); automatic repository updates are not supported by the format (manual update required)",
"{} managed AppImage(s); automatic repository updates are not supported by the format (manual update required)", appimages.len()
appimages.len() ),
), });
});
}
// 5. Nix // 5. Nix
if lane_selected(filter, Backend::Nix) { let nix_installed = crate::nix::installed(root);
let nix_installed = crate::nix::installed(root); sources.push(SourceUpdateOverview {
sources.push(SourceUpdateOverview { backend: Backend::Nix,
backend: Backend::Nix, updates: Vec::new(),
updates: Vec::new(), supported: nix_installed,
supported: nix_installed, note: if nix_installed {
note: if nix_installed { "Nix dev packages are declarative/pinned; updates are managed per-project or via profile updates".into()
"Nix dev packages are declarative/pinned; updates are managed per-project or via profile updates".into() } else {
} else { "Nix is not installed".into()
"Nix is not installed".into() },
}, });
});
}
// Reboot check: check /var/run/reboot-required // Reboot check: check /var/run/reboot-required
let reboot_required = root.join("var/run/reboot-required").exists(); let reboot_required = root.join("var/run/reboot-required").exists();

View file

@ -442,7 +442,6 @@ fn validate_effect_bindings(plan: &PreparedPlan, steps: &[ResolvedPlan]) -> Resu
}; };
for step in steps { for step in steps {
combined.effects.extend(step.effects.clone()); combined.effects.extend(step.effects.clone());
combined.cleanup.extend(step.cleanup.clone());
combined.consequences.extend(step.consequences.clone()); combined.consequences.extend(step.consequences.clone());
} }
combined.recompute_digest(); combined.recompute_digest();
@ -1153,45 +1152,6 @@ fn constrain_action(
SystemAction::CleanCache { .. } => SystemAction::CleanCache { SystemAction::CleanCache { .. } => SystemAction::CleanCache {
backend: Some(constraint), backend: Some(constraint),
}, },
// Optional-backend discovery and selection requests must be *rewritten*
// to the constraint, not merely filtered afterwards: otherwise the
// resolver would still query every lane before the results are
// discarded.
SystemAction::DiscoverCandidates {
query,
kind,
gui,
requires_sandbox,
..
} => SystemAction::DiscoverCandidates {
query,
kind,
backend: Some(constraint),
gui,
requires_sandbox,
},
SystemAction::ChoosePackage {
name,
kind,
gui,
requires_sandbox,
..
} => SystemAction::ChoosePackage {
name,
kind,
backend: Some(constraint),
gui,
requires_sandbox,
},
// `InspectInstallation` has no lane field but probes every lane; under
// an explicit constraint it is refused rather than leaking other lanes.
SystemAction::InspectInstallation { .. } => {
return Err(format!(
"inspect_installation spans every package lane, but this request was constrained \
to {}; use a lane-specific inventory instead",
constraint.as_str()
));
}
other => { other => {
if let Some(own) = other.backend() { if let Some(own) = other.backend() {
let matches = own == constraint || (own.is_portage() && constraint.is_portage()); let matches = own == constraint || (own.is_portage() && constraint.is_portage());
@ -1304,7 +1264,6 @@ pub fn plan_general(
eff.recompute_digest(); eff.recompute_digest();
if eff.established { if eff.established {
combined_effects.effects.extend(eff.effects.clone()); combined_effects.effects.extend(eff.effects.clone());
combined_effects.cleanup.extend(eff.cleanup.clone());
combined_effects combined_effects
.consequences .consequences
.extend(eff.consequences.clone()); .extend(eff.consequences.clone());
@ -1587,7 +1546,6 @@ fn revalidate_plan_state(exec: &Exec, root: &Path, plan: &PreparedPlan) -> Resul
let eff = actions::resolve_effects(exec, act, root)?; let eff = actions::resolve_effects(exec, act, root)?;
if eff.established { if eff.established {
combined.effects.extend(eff.effects); combined.effects.extend(eff.effects);
combined.cleanup.extend(eff.cleanup);
combined.consequences.extend(eff.consequences); combined.consequences.extend(eff.consequences);
} }
} }
@ -2514,22 +2472,23 @@ mod tests {
return Ok(ok("installed\n".into())); return Ok(ok("installed\n".into()));
} }
let installed = self.installed.load(std::sync::atomic::Ordering::SeqCst); let installed = self.installed.load(std::sync::atomic::Ordering::SeqCst);
let is_flatpak = spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak"); match spec.program.as_str() {
if is_flatpak && spec.args.iter().any(|a| a == "search") { "flatpak" if spec.args.iter().any(|a| a == "search") => {
Ok(ok("org.mozilla.firefox 128\n".into())) Ok(ok("org.mozilla.firefox 128\n".into()))
} else if is_flatpak && spec.args.iter().any(|a| a == "list") {
if !installed {
return Ok(ok(String::new()));
} }
// `--columns=application` (verification) vs the richer "flatpak" if spec.args.iter().any(|a| a == "list") => {
// `application,name,version` (discovery). if !installed {
if spec.args.iter().any(|a| a == "--columns=application") { return Ok(ok(String::new()));
Ok(ok("org.mozilla.firefox\n".into())) }
} else { // `--columns=application` (verification) vs the richer
Ok(ok("org.mozilla.firefox Firefox 128\n".into())) // `application,name,version` (discovery).
if spec.args.iter().any(|a| a == "--columns=application") {
Ok(ok("org.mozilla.firefox\n".into()))
} else {
Ok(ok("org.mozilla.firefox Firefox 128\n".into()))
}
} }
} else { _ => Ok(ok(String::new())),
Ok(ok(String::new()))
} }
} }
} }
@ -2543,17 +2502,6 @@ mod tests {
Exec::new(runner, logger, false, root.to_path_buf(), temp) Exec::new(runner, logger, false, root.to_path_buf(), temp)
} }
/// A target that actually has a Flatpak client, so lane availability
/// resolves from the target rather than the host.
fn install_fake_flatpak(root: &Path) {
use std::os::unix::fs::PermissionsExt;
let bin = root.join("usr/bin");
std::fs::create_dir_all(&bin).unwrap();
let flatpak = bin.join("flatpak");
std::fs::write(&flatpak, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap();
}
#[test] #[test]
fn install_verification_failure_finishes_the_transaction_as_failed() { fn install_verification_failure_finishes_the_transaction_as_failed() {
let root = tempdir().unwrap(); let root = tempdir().unwrap();
@ -2567,7 +2515,6 @@ mod tests {
); );
let store = PlanStore::with_dir(tempdir().unwrap().keep()); let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
install_fake_flatpak(root.path());
let mut request = InstallRequest::new("firefox"); let mut request = InstallRequest::new("firefox");
request.backend = Some(Backend::Flatpak); request.backend = Some(Backend::Flatpak);
@ -2626,7 +2573,6 @@ mod tests {
); );
let store = PlanStore::with_dir(tempdir().unwrap().keep()); let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep()); let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
install_fake_flatpak(root.path());
let mut request = InstallRequest::new("firefox"); let mut request = InstallRequest::new("firefox");
request.backend = Some(Backend::Flatpak); request.backend = Some(Backend::Flatpak);
let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap(); let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap();
@ -3734,7 +3680,6 @@ mod tests {
}; };
for step in &steps { for step in &steps {
combined.effects.extend(step.effects.clone()); combined.effects.extend(step.effects.clone());
combined.cleanup.extend(step.cleanup.clone());
combined.consequences.extend(step.consequences.clone()); combined.consequences.extend(step.consequences.clone());
} }
combined.recompute_digest(); combined.recompute_digest();
@ -4060,113 +4005,4 @@ mod tests {
}] }]
); );
} }
#[test]
fn effect_binding_aggregates_cleanup_intents_for_a_clean_cache_step() {
let root = tempdir().unwrap();
let mut step = ResolvedPlan {
established: true,
..Default::default()
};
step.cleanup.push(phoebus_core::effects::CleanupEffect {
cleaner: "eclean-dist".into(),
items: vec!["app-misc/one".into()],
unavailable: false,
});
let plan = general_portage_plan(
"plan-cleanup",
vec![SystemAction::CleanCache { backend: None }],
vec![step],
root.path(),
effective_uid(),
);
let steps = reviewed_steps(&plan).unwrap();
validate_effect_bindings(&plan, &steps)
.expect("cleanup intents must aggregate into the bound plan");
}
#[test]
fn constrain_action_rewrites_optional_backend_discovery_before_querying() {
let discover = constrain_action(
SystemAction::DiscoverCandidates {
query: "chrome".into(),
kind: None,
backend: None,
gui: false,
requires_sandbox: false,
},
Backend::Flatpak,
)
.unwrap();
assert_eq!(discover.backend(), Some(Backend::Flatpak));
let choose = constrain_action(
SystemAction::ChoosePackage {
name: "chrome".into(),
kind: None,
backend: None,
gui: false,
requires_sandbox: false,
},
Backend::Flatpak,
)
.unwrap();
assert_eq!(choose.backend(), Some(Backend::Flatpak));
}
#[test]
fn constrain_action_refuses_portage_only_actions_under_another_lane() {
for action in [
SystemAction::RemovePackage {
atom: "www-client/firefox".into(),
},
SystemAction::UpdateSystem,
SystemAction::Depclean,
SystemAction::PackageOwners {
path: "/usr/bin/vim".into(),
},
SystemAction::PackageDependencies {
package: "vim".into(),
reverse: false,
},
SystemAction::InstallPackage {
atom: "vim".into(),
binary: None,
},
SystemAction::InspectPackage { atom: "vim".into() },
] {
let err = constrain_action(action.clone(), Backend::Flatpak).unwrap_err();
assert!(
err.contains("constrained") || err.contains("targets the"),
"{action:?} -> {err}"
);
}
}
#[test]
fn constrain_action_refuses_cross_lane_installation_inspection() {
let err = constrain_action(
SystemAction::InspectInstallation {
application: "firefox".into(),
},
Backend::Flatpak,
)
.unwrap_err();
assert!(err.contains("spans every package lane"), "{err}");
}
#[test]
fn constrain_action_allows_spanning_non_package_actions() {
for action in [
SystemAction::History,
SystemAction::RollbackStatus,
SystemAction::EnableService {
name: "sshd".into(),
},
] {
assert!(constrain_action(action, Backend::Flatpak).is_ok());
}
// A Portage-only action is allowed when the constraint is Portage.
assert!(constrain_action(SystemAction::UpdateSystem, Backend::PortageSource).is_ok());
}
} }

View file

@ -167,25 +167,6 @@ run_expect_zero_contains info-legacy "Package information" --legacy info bash
run_expect_zero_contains updates-legacy "Unified Update Overview" --legacy updates run_expect_zero_contains updates-legacy "Unified Update Overview" --legacy updates
run_expect_zero_contains json-search-legacy "Package catalogue" --legacy --action '{"action":"search_packages","query":"firefox"}' run_expect_zero_contains json-search-legacy "Package catalogue" --legacy --action '{"action":"search_packages","query":"firefox"}'
# Regression: an alternate root must never be answered by the host's Snap lane.
AltRoot="$WORK/altroot"
mkdir -p "$AltRoot"
run_expect_zero_contains snap-alternate-root "alternate root" \
--root "$AltRoot" --legacy search firefox --snap
# Regression: Nix inventory enumerates active profiles, never host commands.
run_expect_zero_contains list-nix-legacy "[nix]" --legacy list --nix
# Regression: dependency inspection uses declared metadata, not a merge plan.
"$SYS" --legacy --action \
'{"action":"package_dependencies","package":"bash","reverse":false}' \
>"$WORK/deps.out" 2>"$WORK/deps.err"
if grep -qE "declares|dependency token|has no declared dependencies" "$WORK/deps.out"; then
report deps-legacy PASS "$(head -c 160 "$WORK/deps.out" | tr '\n' ' ')"
elif grep -qi "app-portage/portage-utils\|qdepends\|not installed" "$WORK/deps.err" "$WORK/deps.out"; then
report deps-legacy PASS "honest limitation: $(head -c 120 "$WORK/deps.err" | tr '\n' ' ')"
else
report deps-legacy FAIL "rc=$? $(head -c 200 "$WORK/deps.err" | tr '\n' ' ')"
fi
# A recognizable catalogue command without --legacy must enter the AI workflow # A recognizable catalogue command without --legacy must enter the AI workflow
# and must not run deterministically when no model is available. # and must not run deterministically when no model is available.
if ! PHOEBUS_AI_PROVIDER="" PHOEBUS_AI_BACKEND=direct \ if ! PHOEBUS_AI_PROVIDER="" PHOEBUS_AI_BACKEND=direct \