feat(sys): complete the package-management interface (search/list/info/updates/maintenance)
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-09-25 03:11:18 -07:00
parent 3005630064
commit 05d7075341
19 changed files with 3787 additions and 245 deletions

View file

@ -3,6 +3,69 @@
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 — 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
still the default for every operation; `--legacy` is the only user-facing opt-in
to deterministic handling.
- **Unified search** (`phoebus-executor::query`, `SystemAction::SearchPackages`
gains an optional `backend`): cross-source discovery across Portage, Flatpak,
Snap, managed AppImages, Nix and staged custom ebuilds. Every lane reports
**unavailable**, **failed**, or **empty** distinctly; no metadata is invented.
`sys search firefox [--legacy] [--<source>]`.
- **Inventory** (`SystemAction::ListPackages`): Portage VDB, `flatpak list`,
`snap list`, managed AppImages, and **Nix profiles** (store paths reported
separately as realised dependencies, never as installed programs). Custom
ebuilds install through Portage and are listed once, under Portage.
`sys list [filter] [--legacy] [--<source>]`.
- **Package information** (`SystemAction::PackageInfo`): installed VDB metadata
(version, size, repository, `RDEPEND`) merged with resolved candidates and
policy metadata; ambiguous queries list every real match and are flagged.
`sys info <package> [--legacy] [--<source>]`. `sys inspect <service>` is
unchanged.
- **Consistent updates** (`CheckUpdates`/`ApplyUpdates`): `sys updates` checks
every lane without mutating; `sys apply updates` reports a truthful
per-source outcome and fails the action when an attempted source fails.
AppImage (pinned URL+SHA) and Nix (project/declarative) are explained as
manual/project-specific, never reported as updated. Background preparation
stays distinct from activation. Portage updates/depclean are previewed from
`emerge --pretend` at review time.
- **Maintenance** (`Depclean`, `CleanCache`, `PackageOwners`,
`PackageDependencies`): unused-dependency removal, Portage/Nix cache cleanup,
package-file ownership (`qfile`/`equery`), and forward/reverse dependency
inspection, all with explicit unsupported results where a backend or tool
cannot support them.
- **AI-default routing enforced**: a recognizable catalogue command enters the
general assistant loop (`phoebus_ai::assistant::run_assistant`), which may run
bounded read-only tools before answering. An explicit source flag is applied
to both investigation requests and the final plan (rewriting lane-selectable
queries, refusing a foreign lane). A missing model or provider failure stops
the workflow and prints the exact `--legacy` alternative; it never executes
deterministically. Direct JSON still requires `--legacy`/`--broker`.
- **Tests:** +43 (core/executor/ai/installer) covering search/list/info parsing
and dispatch, unavailable/failed/empty distinction, VDB metadata, ambiguity,
depclean preview and skip, per-source update failure, no double-counting,
routing (AI vs legacy), the source constraint, and the general investigation
loop. `installer/tests/vm/sys-acceptance.sh` gains catalogue and
routing cases (read-only group now 34).
- **VM-verified (disposable installed disk):** `installer/tests/vm/sys-acceptance.sh`
reports `SUMMARY PASS=34 FAIL=0`, including `search-legacy`, `list-legacy`,
`info-legacy`, `updates-legacy`, `search-no-model-offer`,
`search-flag-constraint` and the non-root maintenance refusals.
- **Fixed: read-only Portage queries failed for a normal account.** The
installed system left `/etc/portage/repos.conf` and
`/etc/portage/package.use/phoebus` root-only, so `emerge --search` and
`emerge --depclean --pretend` failed with `Permission denied` for the
unprivileged catalogue. `portage::normalize_config_permissions` makes the
non-secret Portage configuration world-readable (0755 dirs, 0644 files) while
leaving the keyring (`/etc/portage/gnupg`, key-holding files) private; it runs
when the config is written and again at finalize. Unit-tested (including the
keyring exclusion); demonstrated on the disposable VM by applying the same
permissions, after which `sys search firefox --legacy` returns real results
and `sys updates --legacy` reports the available updates. A fresh VM install
with the fix is not yet re-run (base install is ~2 h).
## 2026-09-25 — Installed-VM verification fixes (installer finalize probe, personal preference transactions) ## 2026-09-25 — Installed-VM verification fixes (installer finalize probe, personal preference transactions)
Found while running the acceptance on a fresh disposable installed system: Found while running the acceptance on a fresh disposable installed system:

View file

@ -3,110 +3,95 @@
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), adversarial hardening of the - **Last updated:** this session (2026-09-25), completion of the `sys`
privileged approval boundary: (1) the broker recomputes the canonical package-management interface: unified cross-source search, installed-package
approval digest for every plan kind, (2) the ledger uses a stable approval inventory, package information, consistent per-source update check/apply, and
identity instead of the editable integrity seal, (3) crash recovery is maintenance (depclean/cache/owners/deps), all as validated typed actions
live-safe and terminal transitions are atomic/monotonic, and (4) personal shared by the CLI and assistant. AI remains the default for every operation;
writes are owned by the initiating user. See ADR 0014. Supersedes the `--legacy` is the only user-facing opt-in to deterministic handling. A source
`0be3010` approval design; that commit's UX/docs changes are preserved. flag constrains the AI workflow and never bypasses it. See
`docs/SYS.md` "Package catalogue" and the CHANGELOG entry.
- **Current focus:** - **Current focus:**
1. **Canonical digest at the privileged boundary (`service::validate_prepared_plan`):** 1. **New typed actions (`phoebus-core::action`):** `SearchPackages` gained an
- Independently re-derives `compute_plan_digest(actions, candidate, optional `backend`; added `ListPackages`, `PackageInfo`, `PackageOwners`,
effects, step_effects)` and requires it to equal both `plan.digest` and `PackageDependencies`, `Depclean`, `CleanCache`, `CheckUpdates`,
the supplied `--approval-digest`. Covers Install, LegacyInstall, Removal, `ApplyUpdates`. Read-only variants are non-mutating and need no root;
General and Undo. The stored `integrity` seal is only a self-consistency `ApplyUpdates`/`Depclean` are High risk (protective snapshot), `CleanCache`
check and is never treated as authentication. Medium.
- **Per-step effect binding:** execution trusts `step_effects`, so the 2. **Executor catalogue (`phoebus-executor::query`, `phoebus-core::catalog`):**
canonical digest now hashes every step (contents recomputed, not read search/inventory/info across Portage, Flatpak, Snap, managed AppImages, Nix
from the stored digest); each stored step digest must match its contents, and staged custom ebuilds. Each lane reports unavailable / failed / empty
and the aggregate must be the concatenation of the steps. A multi-action distinctly. Nix profiles are listed; store paths are reported separately as
plan without per-step effects is refused. Install/LegacyInstall keep the realised dependencies. Custom ebuilds are never double-counted (they appear
install-specific digest with the single step required to equal the under Portage). Portage VDB reading (`portage::installed_packages`) and
aggregate. This closes the "retain the approved digest, change only `emerge --search` parsing (`portage::parse_search`) added.
`step_effects`, recompute the seal" gap; rejected before any command runs 3. **Updates + maintenance:** `check_updates` filters the unified overview;
or approval is consumed. The earlier-step allowance in `approval_holds` `apply_updates` runs each lane and returns a truthful per-source report,
is unchanged. failing the action when an attempted source fails; AppImage/Nix are
2. **Stable approval identity (`phoebus_installer::approval`, ADR 0014):** explained as manual/project-specific. `depclean` and Portage `ApplyUpdates`
- Ledger + `.claim` key = `approval_key(plan_id, canonical_digest, are previewed from `emerge --pretend` at review time and bound by digest.
initiator_uid, target_root)`. Presentation fields (summary, rationale, 4. **AI-default routing (`phoebus-ai::assistant::run_assistant`):** the general
verification) are excluded, so editing them and resealing cannot mint a assistant now runs a bounded read-only investigation loop
fresh record for a consumed approval; a newly reviewed identical (`kind:"investigate"` / `kind:"plan"`, `parse_step`, `is_general_investigation_action`)
operation with a new plan id is allowed. before answering. `service::plan_general` supplies the read-only executor,
- Claims record the owning process (`pid`, `/proc/<pid>/stat` start ticks, applies the source constraint to investigation requests and the final plan
boot id). Terminal status is published once via an atomic hard link into (`constrain_action`: rewrite lane-selectable queries, refuse a foreign
`<key>.terminal` and is immutable. `reconcile_interrupted` only marks a lane), and accepts an empty action list as a pure answer. `sys` renders an
record interrupted when the owner is provably gone, so a live operation answer without executing; a missing model prints the exact `--legacy`
(or a second broker starting concurrently) is never mislabelled, and it command.
cannot race a real `finish`.
3. **Personal write ownership (`phoebus_executor::personal`):**
- `write_private` creates the config/state path one component at a time
under the resolved home, rejecting symlinks and non-directories.
- Elevated writes (effective root on behalf of a non-root user) chown the
created paths to the initiating user's uid/gid (via a standard-library
`chown` behind an injectable `OwnerFixer`). A non-root process acting for
a different user is refused. Proactive state now routes through the same
path.
4. **Reviewed effects + terminal transactions** (`service::execute_prepared`,
unchanged this session): reviewed per-step effects are carried forward and
freshly resolved effects are evidence compared with
`phoebus_core::effects::approval_holds`; every path after
`transaction::begin` reaches a terminal result.
- **Last verified (this session):** - **Last verified (this session):**
- `cargo fmt --all -- --check` clean. - `cargo fmt --all -- --check` clean; `cargo clippy --workspace --all-targets`
- `cargo test --workspace`: 602 passed, 0 failed. New per-step binding exits 0 (only pre-existing lints remain).
adversarial tests: single-action and multi-action General plans with - `cargo test --workspace`: 645 passed, 0 failed (was 602). New coverage
`step_effects` swapped (with and without a matching aggregate) while the includes: catalogue action classification/validation and natural phrases;
approved digest is retained are rejected before any command, ledger claim or catalogue report rendering (unavailable/failed/empty, installed/scope);
transaction; a legitimate bound multi-step plan still validates. New CLI per-lane search/inventory/info with a recording runner; VDB metadata and
regression: a personal preference succeeds when the system transaction no-double-count; ambiguity; depclean preview/skip; per-source update
directory is read-only. The prior session's adversarial tests all still pass. failure; forward dependencies; AI step parsing, the general investigation
- `cargo clippy --workspace --all-targets` exits 0 (only the pre-existing loop, mutating-investigation refusal; `plan_general` investigation/answer,
`result_large_err`, one arg-count and one `DiskPhase` lints remain). foreign-lane refusal and constraint rewrite; and CLI routing: search/list/
- `cargo build --release -p phoebus-installer` clean. info/updates without `--legacy` enter the AI workflow and never run
- **Disposable installed VM, clean install (`verify-disk2.qcow2`, qcow2, deterministically, a source flag constrains and never bypasses, `--legacy`
detached boot):** the fixed installer completes with `===INSTALL-RC=0===`, never contacts a model, read-only catalogue commands need no root and write
`installation finished`, `stage complete: finalize`, and `NO_SECRET_LEAK`. no transaction.
Detached boot: LUKS unlock + login; PID 1 `systemd`, - Host smoke test of `sys search/list/info/updates --legacy` against the live
`systemd is-system-running = running`; `sys 0.1.0`; `sys history --legacy` host (real Flatpak inventory and update list rendered).
exit 0; `installer/tests/vm/sys-acceptance.sh` with the fixed `sys` reports - **Disposable-VM read-only acceptance** (`serial-driver.py boot` on a qcow2
`SUMMARY PASS=24 FAIL=0`, including `personal-preference PASS saved to user clone of the installed disk, `SYS_BIN=/tmp/sys`): `sys-acceptance.sh`
config` and `nonroot-systemwide` correctly refused. reports `SUMMARY PASS=34 FAIL=0`, including `search-legacy`, `list-legacy`,
- Two defects found and fixed by the VM runs: (a) the installer `finalize` `info-legacy`, `updates-legacy`, `search-no-model-offer`,
`sys` probe ran the AI-first `sys history` and aborted a `--no-ai` install `search-flag-constraint`, and the non-root maintenance refusals. Found and
with `INSTALL-RC=1`; it now runs `sys history --legacy` fixed a real defect: the installed system left `/etc/portage/repos.conf` and
(`phoebus-executor::sys_runtime`, unit-tested) and the clean install `/etc/portage/package.use/phoebus` root-only, so `emerge --search` failed for
completed; (b) a personal preference wrote the preference but then failed a normal account. `portage::normalize_config_permissions` (unit-tested,
recording it in the root-owned `/var/lib/phoebus/transactions.toml`; keyring excluded) makes the non-secret Portage config world-readable and
personal preferences are now excluded from the system transaction history runs at config write and at finalize; with the same permissions applied to
(CLI regression with a read-only transaction directory). the clone, `search-legacy` returns real results (3) and `updates-legacy`
reports 10 available. The fresh-install re-run is pending (base install is
~2 h).
- **Not yet verified (BLOCKED):** - **Not yet verified (BLOCKED):**
- The privileged `sys --broker --execute-plan` path and replay rejection were - **A fresh VM install with the permission fix** (so the catalogue works
**not** exercised end-to-end in the VM: the serial console has no root out of the box) has not been re-run; the base install is ~2 h. The fix is
access and no Polkit agent (`sudo -n` denied), so `pkexec` elevation cannot unit-tested and its effect was demonstrated on the disposable clone.
complete. These paths remain unit-tested at the `execute_plan_privileged` - **Mutating catalogue journeys** (`apply updates`, `depclean`, `clean cache`)
entry point (replacement, recomputed digest, `step_effects` tampering, are not exercised in a VM; they need a disposable installed disk and, for
replay, concurrency, interruption). A graphical/seat-providing VM or a `apply updates`, network.
passwordless-sudo test image is required for the end-to-end run. - The privileged `sys --broker --execute-plan` path and replay rejection remain
unit-tested only: the serial console has no root access and no Polkit agent
(`sudo -n` denied), so `pkexec` elevation cannot complete. A
graphical/seat-providing VM or a passwordless-sudo test image is required.
- No AI provider credential is present; do not invent one. The general
investigation loop is fixture-verified (scripted transport), not live.
- The pre-existing `test-disk.qcow2` still cannot be unlocked (unknown - The pre-existing `test-disk.qcow2` still cannot be unlocked (unknown
passphrase); do not guess or brute-force. passphrase); do not guess or brute-force.
- No AI provider credential is present; do not invent one. - A real privileged `chown` could not be exercised on this unprivileged host;
- A real privileged `chown` (running as root) could not be exercised on this verified through the injectable fixer seam and the cross-uid refusal test.
unprivileged host; verified through the injectable fixer seam and the
cross-uid refusal test.
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os> - **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222). (remote `origin`, SSH port 2222).
## Next actions (in order) ## Next actions (in order)
1. **Privileged `--broker` acceptance in a seat-providing VM.** The read-only 1. **Installed-VM read-only acceptance of the catalogue** on the booted disk:
acceptance and personal preferences are verified on the clean install
(`verify-disk2.qcow2`, 24/24). 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; the serial console cannot elevate.
2. **Installed `sys` acceptance** on the booted disk:
```sh ```sh
# serve the static sys first: # serve the static sys first:
cp installer-rs/target/x86_64-unknown-linux-gnu/release/sys /home/dominic/vmlab/serve/ cp installer-rs/target/x86_64-unknown-linux-gnu/release/sys /home/dominic/vmlab/serve/
@ -116,10 +101,15 @@ commit it. It should be short and current; use `git log` for detail.
BOOT_CHECKS='... curl .../sys ...; SYS_BIN=/tmp/sys bash .../sys-acceptance.sh ...' \ BOOT_CHECKS='... curl .../sys ...; SYS_BIN=/tmp/sys bash .../sys-acceptance.sh ...' \
python3 installer/tests/vm/serial-driver.py boot python3 installer/tests/vm/serial-driver.py boot
``` ```
The new broker behaviour (replacement during authentication, replay after Expect `SUMMARY PASS=34 FAIL=0` (non-root), including the `search-legacy`,
deleting user plan state, cancellation) is already covered by `list-legacy`, `info-legacy`, `updates-legacy`, `search-no-model-offer`,
`phoebus-installer` unit tests; the installed run confirms the sealed `search-flag-constraint` and non-root maintenance cases. Already run this
elevation path and the personal-preference acceptance case. 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 3. **AI-selected install journey (needs an authorised provider)**: boot the
installed disk, serve the built `sys` and a 0600 key file, then: installed disk, serve the built `sys` and a 0600 key file, then:
```sh ```sh

View file

@ -93,7 +93,8 @@ 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=24 FAIL=0`) | 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 (disposable VM: search returns real results after normalisation; fresh-install re-run pending) | 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 | | Privileged `--broker` plan execution + replay rejection in a VM | yes | yes (privileged entry point) | no (needs root/Polkit agent; unit-tested only) | 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 |
@ -112,6 +113,12 @@ still not VM-verified.
| `sys` consistent target-root execution | yes | yes | no | no | | `sys` consistent target-root execution | yes | yes | no | no |
| `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 |
| 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) | no | 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 (Portage/Nix; unsupported reported explicitly) | no | no |
| AI-default catalogue routing (source flags constrain, never bypass) | yes | yes (investigation loop, constraint rewrite/refusal, fallback offers exact `--legacy` command) | no | 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 |
@ -203,10 +210,11 @@ still not VM-verified.
- **The installed `sys` binary and desktop assistant (`phoebus-assistant`)**: The - **The installed `sys` binary and desktop assistant (`phoebus-assistant`)**: The
installer provisions `sys` into `/usr/local/bin/sys` and configures the desktop installer provisions `sys` into `/usr/local/bin/sys` and configures the desktop
assistant Quickshell application (`phoebus-assistant`) launched via desktop assistant Quickshell application (`phoebus-assistant`) launched via desktop
entries and keybindings. On the installed system, all 22 acceptance test cases entries and keybindings. On the installed system, all 34 acceptance test cases
in `installer/tests/vm/sys-acceptance.sh` pass cleanly (`PASS=22 FAIL=0`), in `installer/tests/vm/sys-acceptance.sh` pass cleanly (`PASS=34 FAIL=0`),
verifying the unified AI-first CLI/GUI interface, deterministic `--legacy` verifying the unified AI-first CLI/GUI interface, deterministic `--legacy`
mode, fail-closed source requirements, audited `--broker`/`--legacy` gates, mode, the package catalogue (search/inventory/information/update-check),
fail-closed source requirements, audited `--broker`/`--legacy` gates,
proactive system monitors, and offline fallback guidance. proactive system monitors, and offline fallback guidance.
- **UKI** is deferred; the dracut UKI generator did not embed the kernel - **UKI** is deferred; the dracut UKI generator did not embed the kernel
command line, so BLS is used (and verified). command line, so BLS is used (and verified).

View file

@ -241,6 +241,85 @@ content; it does not build it. `custom_ebuild_install` requires that same
digest, regenerates the `Manifest` and builds through Portage with its sandbox digest, regenerates the `Manifest` and builds through Portage with its sandbox
enabled. Editing the staged ebuild invalidates the approval. enabled. Editing the staged ebuild invalidates the approval.
### Package catalogue: search, inventory, information, updates, maintenance
These are AI-first like every other operation. Without `--legacy` the request
enters the connected model, which answers from **bounded, read-only evidence**
(search, inventory, information, update checks). A source flag
(`--portage`/`--flatpak`/`--nix`/`--snap`/`--appimage`/`--ebuild`) constrains the
AI workflow: lane-selectable queries are rewritten to that lane and an action
for any other lane is refused. It never bypasses the model. `--legacy` runs the
same typed action deterministically with no model interaction.
Every result distinguishes three honest states per lane: **unavailable**
(tooling absent), **failed** (the tool ran and did not answer), and **empty**
(a successful query with no results). Package facts are never invented.
| Phrase | Typed action | Kind |
| --- | --- | --- |
| `search firefox` / `find firefox` | `search_packages` | read |
| `list` / `list installed` / `list vim` | `list_packages` | read |
| `info firefox` | `package_info` | read |
| `updates` / `check updates` | `check_updates` | read |
| `apply updates` / `upgrade` | `apply_updates` | mutate |
| `depclean` / `autoremove` | `depclean` | mutate |
| `clean cache` / `clean distfiles` | `clean_cache` | mutate |
| `who owns /usr/bin/vim` | `package_owners` | read |
| `deps vim` | `package_dependencies` (reverse=false) | read |
| `rdeps vim` | `package_dependencies` (reverse=true) | read |
Deterministic forms:
```sh
sys search firefox --legacy # every source
sys search firefox --legacy --flatpak # one source
sys list --legacy # installed inventory, all lanes
sys list vim --legacy --portage # inventory, source + text filter
sys info firefox --legacy # version/source/status/deps/size
sys updates --legacy # check only, no mutation
sys apply updates --legacy # apply, per-source outcome
sys depclean --legacy # Portage unused-dependency removal
sys clean cache --legacy --nix # Nix GC
sys who owns /usr/bin/vim --legacy # Portage file ownership
sys deps vim --legacy # forward dependencies
sys rdeps vim --legacy # reverse dependencies (equery)
```
- **Search** covers Portage (`emerge --search`), Flatpak remote search, the Snap
Store, Phoebus-managed AppImages, Nix (`nix search`, when online) and staged
custom ebuilds. Entries show source, identity, version, description and
installed status where the backend provides them.
- **Inventory** covers the Portage VDB, `flatpak list`, `snap list`,
Phoebus-managed AppImages and **Nix profiles**. Nix store paths are reported
separately as realised dependencies, never as installed programs. Custom
ebuilds install through Portage and are listed once, under Portage.
- **Information** combines installed copies (VDB metadata: version, size,
repository, `RDEPEND`) with resolved candidates and policy metadata. When more
than one real package matches, the report is marked **ambiguous** and lists
every match instead of guessing.
- **Updates** check every supported lane. Applying updates reports a truthful
per-source outcome; AppImage (pinned URL+SHA) and Nix (project/declarative)
are explained as manual/project-specific and are never reported as updated. A
source that was attempted and failed fails the whole action while the report
still shows the sources that succeeded. Background **preparation**
(`prepare updates`, `what are you compiling`) remains distinct from
**activation**.
- **Maintenance**: `depclean` previews its removal set with
`emerge --pretend --depclean` at review time and refuses when nothing is
selected; it preserves config files and user data. `clean cache` uses
`eclean-dist`/`eclean-pkg` (Portage) or `nix-store --gc` (Nix) and never
removes an installed package. `package_owners` and `package_dependencies`
require `app-portage/portage-utils`/`gentoolkit` and report an explicit
unsupported error when the tool is absent.
- `sys inspect <service> --legacy` is unchanged: `inspect` always means service
inspection (use `info` for packages).
Read-only catalogue actions (`search_packages`, `list_packages`,
`package_info`, `check_updates`, `package_owners`, `package_dependencies`) need
no root and write no transaction. `apply_updates`, `depclean` and `clean_cache`
are mutating, require root, take a protective snapshot where available, and are
recorded.
### Snapshots and rollback ### Snapshots and rollback
| Phrase | Typed action | Kind | | Phrase | Typed action | Kind |
@ -389,6 +468,16 @@ with no network and no model.
| 21 | Source flag without install | `sys --flatpak history --legacy` | rejected by CLI | | 21 | Source flag without install | `sys --flatpak history --legacy` | rejected by CLI |
| 22 | Unqualified with no model | `sys install firefox` (no provider) | deterministic offer printed, nothing installed | | 22 | Unqualified with no model | `sys install firefox` (no provider) | deterministic offer printed, nothing installed |
| 23 | Read-only investigation | `--legacy --action '{"action":"check_backend",...}'` | structured JSON evidence returned | | 23 | Read-only investigation | `--legacy --action '{"action":"check_backend",...}'` | structured JSON evidence returned |
| 24 | Legacy unified search | `sys search firefox --legacy` | "Package catalogue", exit 0 |
| 25 | Legacy inventory | `sys list --legacy` | "Package catalogue", exit 0 |
| 26 | Legacy package information | `sys info bash --legacy` | "Package information", exit 0 |
| 27 | Legacy update check | `sys updates --legacy` | "Unified Update Overview", exit 0 |
| 28 | Legacy JSON search | `--legacy --action '{"action":"search_packages","query":"firefox"}'` | catalogue, exit 0 |
| 29 | Search without a model | `sys search firefox` (no provider) | nonzero; exact `sys search firefox --legacy` offered; nothing searched |
| 30 | Source flag constrains the AI | `sys search firefox --flatpak` (no provider) | nonzero; `... --legacy --flatpak` offered; not bypassed |
| 31 | Non-root depclean | `sys depclean --legacy` (non-root) | requires root, nonzero |
| 32 | Non-root apply updates | `sys apply updates --legacy` (non-root) | requires root, nonzero |
| 33 | Non-root cache cleanup | `sys clean cache --legacy` (non-root) | requires root, nonzero |
### Mutating acceptance cases (disposable VM only) ### Mutating acceptance cases (disposable VM only)
@ -397,13 +486,14 @@ When `SYS_ACCEPTANCE_MUTATE=1` is set in the disposable VM:
- `mutate-remove`: `sys -y remove app-misc/hello --legacy` uninstalls cleanly. - `mutate-remove`: `sys -y remove app-misc/hello --legacy` uninstalls cleanly.
- `mutate-history`: `sys history --legacy` confirms both install and remove are logged. - `mutate-history`: `sys history --legacy` confirms both install and remove are logged.
The read-only and failure acceptance cases (24, including the personal-preference The read-only and failure acceptance cases (33, including the
case) are exercised by the test suite personal-preference case and the catalogue group) are exercised by the test
(`installer/tests/vm/sys-acceptance.sh`); the broker approval/replay regression suite (`installer/tests/vm/sys-acceptance.sh`); the broker approval/replay
is covered by `phoebus-installer` unit tests. Host unit and regression is covered by `phoebus-installer` unit tests. Host unit and
integration tests in `crates/phoebus-installer/tests/sys_cli.rs`, integration tests in `crates/phoebus-installer/tests/sys_cli.rs`,
`crates/phoebus-core/`, and `crates/phoebus-executor/` cover proposal validation, `crates/phoebus-core/`, and `crates/phoebus-executor/` cover proposal validation,
digest matching, lane policy, and cross-source removal. digest matching, lane policy, cross-source removal, catalogue parsing, per-source
failures/ambiguity, the AI-default routing contract, and the source constraint.
## Security properties ## Security properties

View file

@ -9,6 +9,7 @@
use phoebus_core::action::SystemAction; use phoebus_core::action::SystemAction;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::install::Evidence;
use crate::provider::{ChatMessage, ChatRequest, ModelTransport, ProviderKind, SystemFacts}; use crate::provider::{ChatMessage, ChatRequest, ModelTransport, ProviderKind, SystemFacts};
use crate::AiError; use crate::AiError;
@ -65,7 +66,7 @@ pub fn action_tag(action: &SystemAction) -> String {
/// The system prompt for the installed assistant. The action set is closed and /// The system prompt for the installed assistant. The action set is closed and
/// there is no shell or file action. /// there is no shell or file action.
pub const ASSISTANT_PROMPT: &str = "\ pub const ASSISTANT_PROMPT: &str = "\
You are the Phoebus OS system assistant. You can ONLY propose actions from this \ You are the Phoebus OS system assistant. You can ONLY use actions from this \
closed set: inspect_service, enable_service, disable_service, start_service, \ closed set: inspect_service, enable_service, disable_service, start_service, \
stop_service, restart_service, inspect_package, \ stop_service, restart_service, inspect_package, \
install_package, remove_package, search_packages, choose_package, \ install_package, remove_package, search_packages, choose_package, \
@ -75,24 +76,40 @@ snap_remove, snap_list, snap_refresh, snap_connections, appimage_import, \
appimage_acquire, appimage_update, appimage_remove, appimage_info, appimage_list, \ appimage_acquire, appimage_update, appimage_remove, appimage_info, appimage_list, \
custom_ebuild_prepare, custom_ebuild_install, custom_ebuild_remove, \ custom_ebuild_prepare, custom_ebuild_install, custom_ebuild_remove, \
custom_ebuild_list, create_snapshot, undo, rollback_status, history, \ custom_ebuild_list, create_snapshot, undo, rollback_status, history, \
update_system, prepare_updates, inspect_updates. update_system, prepare_updates, inspect_updates, discover_candidates, \
inspect_candidate, check_backend, inspect_installation, list_packages, \
package_info, package_owners, package_dependencies, depclean, clean_cache, \
check_updates, apply_updates.
Reply with ONLY a JSON object: Each reply is ONE JSON object with version 1 and a `kind`:
{\"version\":1,\"summary\":\"...\",\"actions\":[{\"action\":\"...\",...}],\
\"rationale\":[{\"action\":\"...\",\"reason\":\"...\"}]}
Rules: give every action a non-empty reason; prefer inspection before mutation. \ 1. Investigate (read-only evidence): \
Do not choose a software lane by category alone: use choose_package to compare \ {\"version\":1,\"kind\":\"investigate\",\"requests\":[<read-only action>,...]}. \
the available lanes against the machine (architecture, memory, storage, GPU, \ Use this to answer search, inventory, information and update-check requests from \
Wayland) and the user's preferences, or install_package for an explicit Portage \ real evidence. Useful tools: search_packages (query, optional backend), \
request. Base system components (kernel, drivers, systemd, the host graphics and \ discover_candidates, inspect_candidate, check_backend, inspect_installation, \
audio stack, boot tooling) stay under Portage. A custom ebuild is untrusted, \ list_packages (optional backend/filter), package_info, check_updates \
executable content: stage it with custom_ebuild_prepare so a human reviews the \ (optional backend), package_owners, package_dependencies. Never request a \
artifact and its digest; never assume it will build. Never propose disabling \ mutating action as evidence.
verification, enabling ~amd64 globally, weakening LUKS2/Btrfs/systemd/UEFI, or \
any shell, file or arbitrary command action. You do not have a shell, \ 2. Plan or answer: {\"version\":1,\"summary\":\"...\",\"actions\":[...],\
credentials, or access to private files. A human reviews and authenticates every \ \"rationale\":[{\"action\":\"...\",\"reason\":\"...\"}]}. Give every action a \
mutation."; non-empty reason. For a pure question or a search summary, return an empty \
`actions` list and put the answer in `summary`, grounded ONLY in the evidence \
you were given: never invent package names, versions, descriptions, sizes, \
installation status or availability.
Rules: prefer inspection before mutation. Do not choose a software lane by \
category alone: use choose_package to compare the available lanes against the \
machine (architecture, memory, storage, GPU, Wayland) and the user's \
preferences, or install_package for an explicit Portage request. Base system \
components (kernel, drivers, systemd, the host graphics and audio stack, boot \
tooling) stay under Portage. A custom ebuild is untrusted, executable content: \
stage it with custom_ebuild_prepare so a human reviews the artifact and its \
digest; never assume it will build. Never propose disabling verification, \
enabling ~amd64 globally, weakening LUKS2/Btrfs/systemd/UEFI, or any shell, file \
or arbitrary command action. You do not have a shell, credentials, or access to \
private files. A human reviews and authenticates every mutation.";
/// Parse and validate an assistant plan, fail-closed. /// Parse and validate an assistant plan, fail-closed.
pub fn parse_plan(text: &str) -> Result<AssistantPlan, AiError> { pub fn parse_plan(text: &str) -> Result<AssistantPlan, AiError> {
@ -221,6 +238,194 @@ pub fn complete_plan(
} }
} }
/// One step of the general assistant conversation.
#[derive(Debug, Clone, PartialEq)]
pub enum AssistantStep {
/// Read-only evidence the model wants in order to answer.
Investigate { requests: Vec<SystemAction> },
/// A final plan or answer. `actions` may be empty when the reply is purely
/// informational.
Answer(AssistantPlan),
}
/// The closed set of read-only actions the general assistant may request as
/// evidence. Every non-mutating action qualifies; a mutating action never does.
pub fn is_general_investigation_action(action: &SystemAction) -> bool {
!action.is_mutating()
}
/// Parse one general-assistant reply. Absent `kind` defaults to `plan`, so the
/// existing `AssistantPlan` wire format keeps working.
pub fn parse_step(text: &str) -> Result<AssistantStep, AiError> {
let value: serde_json::Value = serde_json::from_str(text)?;
let obj = value
.as_object()
.ok_or_else(|| AiError::Rejected("the reply must be a JSON object".into()))?;
let version = obj
.get("version")
.and_then(|v| v.as_u64())
.ok_or_else(|| AiError::Rejected("missing `version`".into()))?;
if version != 1 {
return Err(AiError::UnsupportedVersion(version as u32));
}
let kind = obj.get("kind").and_then(|k| k.as_str()).unwrap_or("plan");
if kind == "investigate" {
let allowed = ["version", "kind", "requests"];
for key in obj.keys() {
if !allowed.contains(&key.as_str()) {
return Err(AiError::Rejected(format!("unexpected field `{key}`")));
}
}
let requests: Vec<SystemAction> = serde_json::from_value(
obj.get("requests")
.cloned()
.ok_or_else(|| AiError::Rejected("missing `requests`".into()))?,
)?;
if requests.is_empty() {
return Err(AiError::Rejected("empty investigation request".into()));
}
for request in &requests {
if !is_general_investigation_action(request) {
return Err(AiError::Rejected(format!(
"`{}` is not a permitted read-only investigation action",
request.describe()
)));
}
request
.validate()
.map_err(|e| AiError::Rejected(format!("invalid request: {e}")))?;
}
return Ok(AssistantStep::Investigate { requests });
}
if kind != "plan" {
return Err(AiError::Rejected(format!("unknown kind `{kind}`")));
}
// Strip the envelope keys before enforcing the strict plan schema.
let mut plan_value = value.clone();
if let Some(map) = plan_value.as_object_mut() {
map.remove("kind");
map.remove("requests");
}
let plan = parse_plan(&serde_json::to_string(&plan_value)?)?;
Ok(AssistantStep::Answer(plan))
}
/// The system-side half of the general loop: execute read-only investigation.
pub type GeneralInvestigator<'a> = dyn Fn(&[SystemAction]) -> Vec<Evidence> + 'a;
/// Run the bounded general assistant loop. The model may investigate with
/// read-only tools before returning an answer or plan. Unknown, malformed or
/// mutating replies are rejected; the reply may be corrected once per turn.
#[allow(clippy::too_many_arguments)]
pub fn run_assistant(
provider: ProviderKind,
endpoint: &str,
model: &str,
facts: &SystemFacts,
instruction: &str,
transport: &dyn ModelTransport,
investigate: &GeneralInvestigator,
limits: &crate::install::Limits,
) -> Result<AssistantPlan, AiError> {
if provider == ProviderKind::None {
return Err(AiError::ProviderUnavailable(
"no AI provider selected".into(),
));
}
crate::provider::validate_endpoint(endpoint)?;
facts.validate_no_forbidden()?;
let mut chat = build_request(provider, model, facts, instruction);
let mut repeated: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let mut turns = 0usize;
let mut corrected = false;
while turns < limits.max_turns {
turns += 1;
let body = serde_json::to_string(&chat)?;
let response = transport.send(provider, endpoint, &body)?;
let content = crate::provider::extract_content(&response)?;
let step = match parse_step(&content) {
Ok(step) => step,
Err(e) if !corrected => {
corrected = true;
chat.messages.push(ChatMessage {
role: "assistant".into(),
content: content.clone(),
});
chat.messages.push(ChatMessage {
role: "user".into(),
content: format!(
"Your previous reply was rejected: {e}. Reply with ONLY the \
corrected JSON object, with no prose and no code fence."
),
});
continue;
}
Err(e) => return Err(e),
};
match step {
AssistantStep::Investigate { requests } => {
if requests.len() > limits.max_requests_per_turn {
return Err(AiError::Rejected(format!(
"too many investigation requests in one turn (max {})",
limits.max_requests_per_turn
)));
}
let mut keys: Vec<String> = requests
.iter()
.filter_map(|r| serde_json::to_string(r).ok())
.collect();
keys.sort();
let key = keys.join("|");
let count = repeated.entry(key).or_insert(0);
*count += 1;
chat.messages.push(ChatMessage {
role: "assistant".into(),
content: content.clone(),
});
if *count > limits.max_identical_requests {
chat.messages.push(ChatMessage {
role: "user".into(),
content: "You already requested exactly this evidence; it will not \
be fetched again. Answer now from the evidence you have."
.to_string(),
});
continue;
}
let evidence = investigate(&requests);
let mut payload = String::new();
for item in &evidence {
payload.push_str(&format!(
"Request: {}\nOutput:\n{}\n\n",
item.request, item.output
));
if payload.len() >= limits.max_evidence_bytes {
break;
}
}
if payload.len() > limits.max_evidence_bytes {
payload.truncate(limits.max_evidence_bytes);
payload.push_str("\n[evidence truncated]");
}
chat.messages.push(ChatMessage {
role: "user".into(),
content: format!("Evidence:\n{payload}"),
});
}
AssistantStep::Answer(plan) => return Ok(plan),
}
}
Err(AiError::Rejected(format!(
"the assistant did not answer within {} turns",
limits.max_turns
)))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -403,4 +608,109 @@ mod tests {
assert!(plan.render().contains("choose the best source")); assert!(plan.render().contains("choose the best source"));
assert!(plan.render().contains("install snap thunderbird")); assert!(plan.render().contains("install snap thunderbird"));
} }
#[test]
fn general_step_defaults_to_plan_and_accepts_investigate() {
// No `kind` key: the legacy plan format still parses.
let plan = parse_step(
r#"{"version":1,"summary":"x","actions":[{"action":"history"}],"rationale":[{"action":"history","reason":"asked"}]}"#,
)
.unwrap();
assert!(matches!(plan, AssistantStep::Answer(_)));
let investigate = parse_step(
r#"{"version":1,"kind":"investigate","requests":[{"action":"search_packages","query":"chrome"}]}"#,
)
.unwrap();
match investigate {
AssistantStep::Investigate { requests } => {
assert_eq!(requests.len(), 1);
assert!(matches!(requests[0], SystemAction::SearchPackages { .. }));
}
_ => panic!("expected investigate"),
}
}
#[test]
fn general_investigation_rejects_mutation_and_unknown_kind() {
let err = parse_step(
r#"{"version":1,"kind":"investigate","requests":[{"action":"install_package","atom":"vim"}]}"#,
)
.unwrap_err();
assert!(err.to_string().contains("read-only"));
assert!(parse_step(r#"{"version":1,"kind":"frobnicate","requests":[]}"#).is_err());
assert!(parse_step(r#"{"version":1,"kind":"investigate","requests":[]}"#).is_err());
}
#[test]
fn run_assistant_investigates_then_answers_with_evidence() {
use crate::provider::{chat_response, ScriptedTransport};
let transport = ScriptedTransport::new(vec![
chat_response(
r#"{"version":1,"kind":"investigate","requests":[{"action":"search_packages","query":"chrome"}]}"#,
),
chat_response(r#"{"version":1,"summary":"Real candidates found.","actions":[]}"#),
]);
let calls = std::cell::Cell::new(0);
let investigate = |requests: &[SystemAction]| -> Vec<Evidence> {
calls.set(calls.get() + 1);
requests
.iter()
.map(|r| Evidence {
request: r.describe(),
output: "[{\"source\":\"flatpak\",\"id\":\"com.google.Chrome\"}]".into(),
})
.collect()
};
let plan = run_assistant(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"search chrome",
&transport,
&investigate,
&crate::install::Limits::default(),
)
.unwrap();
assert!(plan.actions.is_empty());
assert_eq!(calls.get(), 1);
let requests = transport.requests();
assert_eq!(requests.len(), 2);
// The evidence must be fed back to the model.
assert!(requests[1].contains("com.google.Chrome"));
}
#[test]
fn run_assistant_never_executes_a_mutating_investigation_request() {
use crate::provider::{chat_response, ScriptedTransport};
// The first reply tries to use a mutation as "evidence"; it is rejected
// and never executed. The corrected reply is a normal plan.
let transport = ScriptedTransport::new(vec![
chat_response(
r#"{"version":1,"kind":"investigate","requests":[{"action":"install_package","atom":"vim"}]}"#,
),
chat_response(
r#"{"version":1,"summary":"Install vim.","actions":[{"action":"install_package","atom":"vim"}],"rationale":[{"action":"install_package","reason":"asked"}]}"#,
),
]);
let executed = std::cell::Cell::new(false);
let investigate = |_: &[SystemAction]| -> Vec<Evidence> {
executed.set(true);
Vec::new()
};
let plan = run_assistant(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install vim",
&transport,
&investigate,
&crate::install::Limits::default(),
)
.unwrap();
assert_eq!(plan.actions.len(), 1);
assert!(!executed.get(), "a mutating request must never be executed");
}
} }

View file

@ -62,6 +62,10 @@ pub enum SystemAction {
}, },
SearchPackages { SearchPackages {
query: String, query: String,
/// Constrain the search to one lane. `None` searches every available
/// source.
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
}, },
/// Install a sandboxed Flatpak application from flathub. /// Install a sandboxed Flatpak application from flathub.
FlatpakInstall { FlatpakInstall {
@ -155,6 +159,58 @@ pub enum SystemAction {
application: String, application: String,
}, },
// ------------------------------------------------------------------
// Package catalogue: inventory, information and maintenance. These are
// read-only except for depclean/cache cleanup, which are explicitly
// separated and previewed.
// ------------------------------------------------------------------
/// List installed packages across the available lanes. A `filter`
/// substrings the identity/description; `backend` restricts the lane.
ListPackages {
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
#[serde(default, skip_serializing_if = "Option::is_none")]
filter: Option<String>,
},
/// Detailed information about a package, installed or available. An
/// ambiguous query reports every match instead of guessing.
PackageInfo {
package: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
},
/// Which installed package(s) own a file path (Portage).
PackageOwners {
path: String,
},
/// Forward or reverse dependencies of a package (where the lane supports
/// it).
PackageDependencies {
package: String,
/// Reverse dependencies instead of forward dependencies.
#[serde(default)]
reverse: bool,
},
/// Remove packages no longer required by any installed package (Portage).
Depclean,
/// Remove unreferenced package caches / store paths (Portage distfiles,
/// Nix store). Never removes an installed package.
CleanCache {
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
},
/// Check for available updates across the supported lanes without changing
/// anything.
CheckUpdates {
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
},
/// Apply available updates across the supported lanes.
ApplyUpdates {
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
},
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Snap lane. // Snap lane.
// ------------------------------------------------------------------ // ------------------------------------------------------------------
@ -267,9 +323,10 @@ impl SystemAction {
} }
} }
SystemAction::RemovePackage { atom } => format!("remove package {atom}"), SystemAction::RemovePackage { atom } => format!("remove package {atom}"),
SystemAction::SearchPackages { query } => { SystemAction::SearchPackages { query, backend } => match backend {
format!("search packages for `{query}`") Some(backend) => format!("search {} for `{query}`", backend.as_str()),
} None => format!("search all package sources for `{query}`"),
},
SystemAction::FlatpakInstall { app_id } => { SystemAction::FlatpakInstall { app_id } => {
format!("install Flatpak app {app_id} from flathub") format!("install Flatpak app {app_id} from flathub")
} }
@ -333,6 +390,43 @@ impl SystemAction {
SystemAction::InspectInstallation { application } => { SystemAction::InspectInstallation { application } => {
format!("inspect existing installations of {application}") format!("inspect existing installations of {application}")
} }
SystemAction::ListPackages { backend, filter } => {
let mut s = match backend {
Some(backend) => format!("list installed {} packages", backend.as_str()),
None => "list installed packages".to_string(),
};
if let Some(filter) = filter {
s.push_str(&format!(" matching `{filter}`"));
}
s
}
SystemAction::PackageInfo { package, backend } => match backend {
Some(backend) => format!("show {} information for {package}", backend.as_str()),
None => format!("show package information for {package}"),
},
SystemAction::PackageOwners { path } => format!("show which package owns {path}"),
SystemAction::PackageDependencies { package, reverse } => {
if *reverse {
format!("show what depends on {package}")
} else {
format!("show the dependencies of {package}")
}
}
SystemAction::Depclean => {
"remove packages no longer required by any installed package".to_string()
}
SystemAction::CleanCache { backend } => match backend {
Some(backend) => format!("clean the {} package cache", backend.as_str()),
None => "clean unreferenced package caches".to_string(),
},
SystemAction::CheckUpdates { backend } => match backend {
Some(backend) => format!("check for {} updates", backend.as_str()),
None => "check for updates across all sources".to_string(),
},
SystemAction::ApplyUpdates { backend } => match backend {
Some(backend) => format!("apply {} updates", backend.as_str()),
None => "apply updates across all sources".to_string(),
},
SystemAction::SnapFind { query } => format!("search the Snap store for `{query}`"), SystemAction::SnapFind { query } => format!("search the Snap store for `{query}`"),
SystemAction::SnapInfo { name } => format!("inspect snap {name}"), SystemAction::SnapInfo { name } => format!("inspect snap {name}"),
SystemAction::SnapInstall { SystemAction::SnapInstall {
@ -412,8 +506,13 @@ impl SystemAction {
| SystemAction::InspectCandidate { .. } | SystemAction::InspectCandidate { .. }
| SystemAction::CheckBackend { .. } | SystemAction::CheckBackend { .. }
| SystemAction::InspectInstallation { .. } | SystemAction::InspectInstallation { .. }
| SystemAction::CustomEbuildList => Risk::Low, | SystemAction::CustomEbuildList
SystemAction::PrepareUpdates => Risk::Medium, | SystemAction::ListPackages { .. }
| SystemAction::PackageInfo { .. }
| SystemAction::PackageOwners { .. }
| SystemAction::PackageDependencies { .. }
| SystemAction::CheckUpdates { .. } => Risk::Low,
SystemAction::PrepareUpdates | SystemAction::CleanCache { .. } => Risk::Medium,
SystemAction::EnableService { .. } SystemAction::EnableService { .. }
| SystemAction::DisableService { .. } | SystemAction::DisableService { .. }
| SystemAction::StartService { .. } | SystemAction::StartService { .. }
@ -435,6 +534,8 @@ impl SystemAction {
SystemAction::InstallPackage { .. } SystemAction::InstallPackage { .. }
| SystemAction::RemovePackage { .. } | SystemAction::RemovePackage { .. }
| SystemAction::UpdateSystem | SystemAction::UpdateSystem
| SystemAction::ApplyUpdates { .. }
| SystemAction::Depclean
| SystemAction::Undo { .. } | SystemAction::Undo { .. }
| SystemAction::CustomEbuildInstall { .. } | SystemAction::CustomEbuildInstall { .. }
| SystemAction::CustomEbuildRemove { .. } => Risk::High, | SystemAction::CustomEbuildRemove { .. } => Risk::High,
@ -465,6 +566,11 @@ impl SystemAction {
| SystemAction::CheckBackend { .. } | SystemAction::CheckBackend { .. }
| SystemAction::InspectInstallation { .. } | SystemAction::InspectInstallation { .. }
| SystemAction::CustomEbuildList | SystemAction::CustomEbuildList
| SystemAction::ListPackages { .. }
| SystemAction::PackageInfo { .. }
| SystemAction::PackageOwners { .. }
| SystemAction::PackageDependencies { .. }
| SystemAction::CheckUpdates { .. }
) )
} }
@ -478,6 +584,50 @@ impl SystemAction {
} }
} }
/// The package lane this action targets, if it is lane-specific. Used to
/// enforce an explicit source filter so a request cannot silently drift to
/// another lane. Actions that span lanes (history, snapshots, services)
/// return `None`.
pub fn backend(&self) -> Option<Backend> {
match self {
SystemAction::SearchPackages { backend, .. }
| SystemAction::ListPackages { backend, .. }
| SystemAction::PackageInfo { backend, .. }
| SystemAction::CleanCache { backend }
| SystemAction::CheckUpdates { backend }
| SystemAction::ApplyUpdates { backend }
| SystemAction::ChoosePackage { backend, .. }
| SystemAction::DiscoverCandidates { backend, .. } => *backend,
SystemAction::InspectCandidate { backend, .. } => Some(*backend),
SystemAction::CheckBackend { backend } => Some(*backend),
SystemAction::InstallPackage { .. } | SystemAction::InspectPackage { .. } => {
Some(Backend::PortageSource)
}
SystemAction::FlatpakInstall { .. }
| SystemAction::FlatpakRemove { .. }
| SystemAction::FlatpakList => Some(Backend::Flatpak),
SystemAction::NixPrepare { .. } => Some(Backend::Nix),
SystemAction::SnapFind { .. }
| SystemAction::SnapInfo { .. }
| SystemAction::SnapInstall { .. }
| SystemAction::SnapRemove { .. }
| SystemAction::SnapList
| SystemAction::SnapRefresh { .. }
| SystemAction::SnapConnections { .. } => Some(Backend::Snap),
SystemAction::AppImageImport { .. }
| SystemAction::AppImageAcquire { .. }
| SystemAction::AppImageUpdate { .. }
| SystemAction::AppImageRemove { .. }
| SystemAction::AppImageInfo { .. }
| SystemAction::AppImageList => Some(Backend::AppImage),
SystemAction::CustomEbuildPrepare { .. }
| SystemAction::CustomEbuildInstall { .. }
| SystemAction::CustomEbuildRemove { .. }
| SystemAction::CustomEbuildList => Some(Backend::CustomEbuild),
_ => None,
}
}
pub fn validate(&self) -> Result<(), String> { pub fn validate(&self) -> Result<(), String> {
let valid_token = |s: &str| { let valid_token = |s: &str| {
!s.is_empty() !s.is_empty()
@ -510,7 +660,7 @@ impl SystemAction {
Err(format!("invalid package name: {atom}")) Err(format!("invalid package name: {atom}"))
} }
} }
SystemAction::SearchPackages { query } => { SystemAction::SearchPackages { query, .. } => {
if valid_search_query(query) { if valid_search_query(query) {
Ok(()) Ok(())
} else { } else {
@ -591,6 +741,37 @@ impl SystemAction {
Err(format!("invalid application name: {application}")) Err(format!("invalid application name: {application}"))
} }
} }
SystemAction::ListPackages { filter, .. } => match filter {
Some(filter) if !valid_search_query(filter) => {
Err(format!("invalid inventory filter: {filter}"))
}
_ => Ok(()),
},
SystemAction::PackageInfo { package, .. } => {
if valid_application_name(package) {
Ok(())
} else {
Err(format!("invalid package name: {package}"))
}
}
SystemAction::PackageOwners { path } => {
if valid_file_path(path) {
Ok(())
} else {
Err(format!("invalid file path: {path}"))
}
}
SystemAction::PackageDependencies { package, .. } => {
if valid_application_name(package) {
Ok(())
} else {
Err(format!("invalid package name: {package}"))
}
}
SystemAction::Depclean
| SystemAction::CleanCache { .. }
| SystemAction::CheckUpdates { .. }
| SystemAction::ApplyUpdates { .. } => Ok(()),
SystemAction::SnapFind { query } => { SystemAction::SnapFind { query } => {
if valid_search_query(query) { if valid_search_query(query) {
Ok(()) Ok(())
@ -836,6 +1017,17 @@ pub fn valid_http_url(value: &str) -> bool {
&& !value.chars().any(|c| c.is_whitespace() || c.is_control()) && !value.chars().any(|c| c.is_whitespace() || c.is_control())
} }
/// An absolute file path for an ownership query: bounded, no NUL or control
/// characters, no shell metacharacters that a backend could misread.
pub fn valid_file_path(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 4096
&& value.starts_with('/')
&& !value.starts_with('-')
&& !value.contains('\0')
&& !value.chars().any(|c| c.is_control())
}
/// A user-facing application name (`firefox`, `org.mozilla.firefox`, /// A user-facing application name (`firefox`, `org.mozilla.firefox`,
/// `app-editors/vim`). Bounded, no leading dash, no whitespace or controls. /// `app-editors/vim`). Bounded, no leading dash, no whitespace or controls.
pub fn valid_application_name(value: &str) -> bool { pub fn valid_application_name(value: &str) -> bool {
@ -992,7 +1184,10 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
} }
if let Some(query) = rest("search ").or_else(|| rest("find ")) { if let Some(query) = rest("search ").or_else(|| rest("find ")) {
if !query.is_empty() { if !query.is_empty() {
return Some(SystemAction::SearchPackages { query }); return Some(SystemAction::SearchPackages {
query,
backend: None,
});
} }
} }
if let Some(name) = rest("inspect ") { if let Some(name) = rest("inspect ") {
@ -1001,6 +1196,91 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
} }
} }
// Package information, inventory and maintenance. These are read-only
// except depclean/clean-cache, which are previewed before removal.
if let Some(package) = rest("info ").or_else(|| rest("package info ")) {
if !package.is_empty() {
return Some(SystemAction::PackageInfo {
package,
backend: None,
});
}
}
if t == "list"
|| t == "list packages"
|| t == "list installed"
|| t == "list installed packages"
|| t == "inventory"
|| t == "installed"
{
return Some(SystemAction::ListPackages {
backend: None,
filter: None,
});
}
if let Some(filter) = rest("list ") {
let filter = filter.trim();
if filter.is_empty() || filter == "packages" || filter == "installed" {
return Some(SystemAction::ListPackages {
backend: None,
filter: None,
});
}
if valid_search_query(filter) {
return Some(SystemAction::ListPackages {
backend: None,
filter: Some(filter.to_string()),
});
}
}
if t == "depclean"
|| t == "autoremove"
|| t == "clean dependencies"
|| t == "remove unused dependencies"
{
return Some(SystemAction::Depclean);
}
if t == "clean cache"
|| t == "clean caches"
|| t == "clean distfiles"
|| t == "clean package cache"
{
return Some(SystemAction::CleanCache { backend: None });
}
if let Some(package) = rest("rdeps ")
.or_else(|| rest("reverse deps "))
.or_else(|| rest("reverse dependencies "))
{
if !package.is_empty() {
return Some(SystemAction::PackageDependencies {
package,
reverse: true,
});
}
}
if let Some(package) = rest("deps ")
.or_else(|| rest("dependencies "))
.or_else(|| rest("what does depend on "))
{
if !package.is_empty() {
return Some(SystemAction::PackageDependencies {
package,
reverse: false,
});
}
}
if let Some(path) = rest("owners ").or_else(|| rest("who owns ")) {
if !path.is_empty() {
return Some(SystemAction::PackageOwners { path });
}
}
if t == "updates" || t == "check updates" || t == "check for updates" || t == "update check" {
return Some(SystemAction::CheckUpdates { backend: None });
}
if t == "apply updates" || t == "upgrade" || t == "upgrade system" || t == "install updates" {
return Some(SystemAction::ApplyUpdates { backend: None });
}
// Flatpak verbs. App ids are case-sensitive (`org.chromium.Chromium`), so // Flatpak verbs. App ids are case-sensitive (`org.chromium.Chromium`), so
// the operands are read from the original text, not the lowercased copy. // the operands are read from the original text, not the lowercased copy.
if let Some(rest) = strip_prefix_ascii_ci(raw, "flatpak ") { if let Some(rest) = strip_prefix_ascii_ci(raw, "flatpak ") {
@ -1366,7 +1646,8 @@ mod tests {
assert_eq!( assert_eq!(
parse_natural("search firefox"), parse_natural("search firefox"),
Some(SystemAction::SearchPackages { Some(SystemAction::SearchPackages {
query: "firefox".into() query: "firefox".into(),
backend: None,
}) })
); );
assert_eq!(parse_natural("why is my audio broken"), None); assert_eq!(parse_natural("why is my audio broken"), None);
@ -1805,4 +2086,123 @@ mod tests {
assert!(valid_ebuild_version("1.2.3-r1")); assert!(valid_ebuild_version("1.2.3-r1"));
assert!(!valid_ebuild_version("../1.0")); assert!(!valid_ebuild_version("../1.0"));
} }
#[test]
fn catalogue_actions_are_typed_and_classified() {
let search =
parse_action(r#"{"action":"search_packages","query":"firefox","backend":"flatpak"}"#)
.unwrap();
assert!(!search.is_mutating());
assert!(!search.requires_root());
assert_eq!(search.risk(), Risk::Low);
assert_eq!(search.backend(), Some(Backend::Flatpak));
let list = parse_action(r#"{"action":"list_packages","filter":"vim"}"#).unwrap();
assert!(!list.is_mutating());
assert_eq!(list.backend(), None);
let info =
parse_action(r#"{"action":"package_info","package":"app-editors/vim"}"#).unwrap();
assert!(!info.is_mutating());
let owners = parse_action(r#"{"action":"package_owners","path":"/usr/bin/vim"}"#).unwrap();
assert!(!owners.is_mutating());
let deps = parse_action(r#"{"action":"package_dependencies","package":"vim"}"#).unwrap();
assert!(!deps.is_mutating());
let check = parse_action(r#"{"action":"check_updates"}"#).unwrap();
assert!(!check.is_mutating());
assert_eq!(check.risk(), Risk::Low);
let apply = parse_action(r#"{"action":"apply_updates"}"#).unwrap();
assert!(apply.is_mutating());
assert!(apply.requires_root());
assert_eq!(apply.risk(), Risk::High);
let depclean = parse_action(r#"{"action":"depclean"}"#).unwrap();
assert!(depclean.is_mutating());
assert_eq!(depclean.risk(), Risk::High);
let clean = parse_action(r#"{"action":"clean_cache","backend":"nix"}"#).unwrap();
assert!(clean.is_mutating());
assert_eq!(clean.risk(), Risk::Medium);
assert_eq!(clean.backend(), Some(Backend::Nix));
}
#[test]
fn catalogue_actions_validate_their_operands() {
assert!(parse_action(r#"{"action":"list_packages","filter":"-C"}"#).is_err());
assert!(parse_action(r#"{"action":"package_info","package":"bad name"}"#).is_err());
assert!(parse_action(r#"{"action":"package_owners","path":"relative"}"#).is_err());
// A control character in the path is rejected before any command.
assert!(parse_action(r#"{"action":"package_owners","path":"/a\u0001b"}"#).is_err());
assert!(parse_action(r#"{"action":"package_dependencies","package":"--flag"}"#).is_err());
assert!(parse_action(r#"{"action":"search_packages","query":""}"#).is_err());
}
#[test]
fn natural_catalogue_phrases_map_to_typed_actions() {
assert_eq!(
parse_natural("list"),
Some(SystemAction::ListPackages {
backend: None,
filter: None
})
);
assert_eq!(
parse_natural("list vim"),
Some(SystemAction::ListPackages {
backend: None,
filter: Some("vim".into())
})
);
assert_eq!(
parse_natural("info firefox"),
Some(SystemAction::PackageInfo {
package: "firefox".into(),
backend: None
})
);
assert_eq!(
parse_natural("updates"),
Some(SystemAction::CheckUpdates { backend: None })
);
assert_eq!(
parse_natural("apply updates"),
Some(SystemAction::ApplyUpdates { backend: None })
);
assert_eq!(parse_natural("depclean"), Some(SystemAction::Depclean));
assert_eq!(
parse_natural("clean cache"),
Some(SystemAction::CleanCache { backend: None })
);
assert_eq!(
parse_natural("who owns /usr/bin/vim"),
Some(SystemAction::PackageOwners {
path: "/usr/bin/vim".into()
})
);
assert_eq!(
parse_natural("deps vim"),
Some(SystemAction::PackageDependencies {
package: "vim".into(),
reverse: false
})
);
assert_eq!(
parse_natural("rdeps vim"),
Some(SystemAction::PackageDependencies {
package: "vim".into(),
reverse: true
})
);
// `inspect` still means the service, preserving existing behaviour.
assert_eq!(
parse_natural("inspect sshd"),
Some(SystemAction::InspectService {
name: "sshd".into()
})
);
}
} }

View file

@ -0,0 +1,386 @@
//! Shared package-catalogue report types.
//!
//! Search, inventory and package information are produced by the executor from
//! real backend metadata and rendered both to the user and to the AI as
//! evidence. They deliberately distinguish three cases for every lane:
//! unavailable (the tooling is not present), failed (the tool ran but did not
//! answer), and genuinely empty (a successful query with no results). No
//! metadata is ever invented.
use serde::{Deserialize, Serialize};
use crate::selection::Backend;
/// One package the catalogue knows about.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogEntry {
/// The lane that would supply or does supply the package.
pub source: Backend,
/// The backend-native identity (Portage atom, Flatpak app id, snap name,
/// managed AppImage name, Nix store/profile path).
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Whether the package is installed in this lane right now.
pub installed: bool,
/// Where the entry came from when a lane has more than one scope. Nix uses
/// `profile` for installed profiles; store-realised paths are reported
/// separately and are not "installed packages".
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
}
impl CatalogEntry {
pub fn new(source: Backend, id: impl Into<String>) -> Self {
Self {
source,
id: id.into(),
version: None,
description: None,
installed: false,
scope: None,
}
}
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn installed(mut self, installed: bool) -> Self {
self.installed = installed;
self
}
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
}
/// The result for one lane.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceReport {
pub backend: Backend,
/// The lane's tooling is present (or the lane is intrinsic).
pub supported: bool,
/// The query ran and produced a trustworthy answer.
pub ok: bool,
/// A short, truthful explanation: why it is unsupported, why it failed, or
/// what the result covers.
pub note: String,
#[serde(default)]
pub entries: Vec<CatalogEntry>,
}
impl SourceReport {
pub fn unsupported(backend: Backend, note: impl Into<String>) -> Self {
Self {
backend,
supported: false,
ok: false,
note: note.into(),
entries: Vec::new(),
}
}
pub fn failed(backend: Backend, note: impl Into<String>) -> Self {
Self {
backend,
supported: true,
ok: false,
note: note.into(),
entries: Vec::new(),
}
}
pub fn ok(backend: Backend, note: impl Into<String>, entries: Vec<CatalogEntry>) -> Self {
Self {
backend,
supported: true,
ok: true,
note: note.into(),
entries,
}
}
}
/// A unified search or inventory report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogReport {
/// The query (or inventory filter); `(all)` for an unfiltered inventory.
pub query: String,
#[serde(default)]
pub sources: Vec<SourceReport>,
}
impl CatalogReport {
pub fn new(query: impl Into<String>) -> Self {
Self {
query: query.into(),
sources: Vec::new(),
}
}
pub fn push(&mut self, report: SourceReport) {
self.sources.push(report);
}
pub fn entries(&self) -> impl Iterator<Item = &CatalogEntry> {
self.sources.iter().flat_map(|s| s.entries.iter())
}
pub fn total(&self) -> usize {
self.entries().count()
}
/// Only a lane that is supported, answered, and returned at least one entry
/// is a positive result.
pub fn has_results(&self) -> bool {
self.sources.iter().any(|s| s.ok && !s.entries.is_empty())
}
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str(&format!("Package catalogue for `{}`\n", self.query));
for source in &self.sources {
if !source.supported {
out.push_str(&format!(
" [{}] unavailable: {}\n",
source.backend.as_str(),
source.note
));
} else if !source.ok {
out.push_str(&format!(
" [{}] search failed: {}\n",
source.backend.as_str(),
source.note
));
} else if source.entries.is_empty() {
out.push_str(&format!(
" [{}] no results ({})\n",
source.backend.as_str(),
source.note
));
} else {
out.push_str(&format!(
" [{}] {} result(s) ({})\n",
source.backend.as_str(),
source.entries.len(),
source.note
));
for entry in &source.entries {
out.push_str(" - ");
out.push_str(&entry.id);
if let Some(version) = &entry.version {
out.push_str(&format!(" {version}"));
}
if let Some(scope) = &entry.scope {
out.push_str(&format!(" [{scope}]"));
}
if entry.installed {
out.push_str(" (installed)");
}
if let Some(description) = &entry.description {
out.push_str(&format!(" — {description}"));
}
out.push('\n');
}
}
}
if !self.has_results() {
out.push_str(" (no matching packages in any available source)\n");
}
out
}
}
/// Detailed information about one package match.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PackageInfoMatch {
pub source: Backend,
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub installed: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dependencies: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub reverse_dependencies: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<String>,
#[serde(default)]
pub provenance: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub permissions: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
/// The result of a package-information query. `ambiguous` is set when more than
/// one distinct candidate matched and the caller must choose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PackageInfoReport {
pub query: String,
#[serde(default)]
pub matches: Vec<PackageInfoMatch>,
pub ambiguous: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
impl PackageInfoReport {
pub fn ambiguous(&self) -> bool {
self.matches.len() > 1
}
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str(&format!("Package information for `{}`\n", self.query));
if self.matches.is_empty() {
out.push_str(" no package matched in any available source\n");
}
for m in &self.matches {
out.push_str(&format!(" - {} ({})\n", m.id, m.source.as_str()));
if let Some(version) = &m.version {
out.push_str(&format!(" version: {version}\n"));
}
out.push_str(&format!(
" installed: {}\n",
if m.installed { "yes" } else { "no" }
));
if let Some(description) = &m.description {
out.push_str(&format!(" description: {description}\n"));
}
if !m.provenance.is_empty() {
out.push_str(&format!(" provenance: {}\n", m.provenance));
}
if let Some(size) = &m.size {
out.push_str(&format!(" size: {size}\n"));
}
if !m.dependencies.is_empty() {
out.push_str(&format!(
" dependencies: {}\n",
m.dependencies.join(", ")
));
}
if !m.reverse_dependencies.is_empty() {
out.push_str(&format!(
" reverse dependencies: {}\n",
m.reverse_dependencies.join(", ")
));
}
if !m.permissions.is_empty() {
out.push_str(&format!(
" permissions: {}\n",
m.permissions.join(", ")
));
}
for note in &m.notes {
out.push_str(&format!(" note: {note}\n"));
}
}
for note in &self.notes {
out.push_str(&format!(" note: {note}\n"));
}
if self.ambiguous() {
out.push_str(
" ambiguous: more than one package matched; choose a source or a full id\n",
);
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_distinguishes_unavailable_failed_and_empty() {
let mut report = CatalogReport::new("firefox");
report.push(SourceReport::unsupported(
Backend::Snap,
"snapd is not installed",
));
report.push(SourceReport::failed(Backend::Flatpak, "flatpak is offline"));
report.push(SourceReport::ok(
Backend::PortageSource,
"gentoo tree",
vec![],
));
let text = report.render();
assert!(text.contains("[snap] unavailable: snapd is not installed"));
assert!(text.contains("[flatpak] search failed: flatpak is offline"));
assert!(text.contains("[portage-source] no results (gentoo tree)"));
assert!(!report.has_results());
}
#[test]
fn render_lists_entries_with_installed_and_scope() {
let mut report = CatalogReport::new("firefox");
report.push(SourceReport::ok(
Backend::PortageSource,
"gentoo tree",
vec![
CatalogEntry::new(Backend::PortageSource, "www-client/firefox")
.version("128.0")
.description("Mozilla Firefox")
.installed(true),
],
));
let text = report.render();
assert!(text.contains("www-client/firefox 128.0 (installed)"));
assert!(text.contains("Mozilla Firefox"));
assert!(report.has_results());
assert_eq!(report.total(), 1);
}
#[test]
fn ambiguous_info_report_flags_multiple_matches() {
let report = PackageInfoReport {
query: "firefox".into(),
matches: vec![
PackageInfoMatch {
source: Backend::PortageSource,
id: "www-client/firefox".into(),
version: None,
description: None,
installed: true,
dependencies: Vec::new(),
reverse_dependencies: Vec::new(),
size: None,
provenance: "gentoo".into(),
permissions: Vec::new(),
notes: Vec::new(),
},
PackageInfoMatch {
source: Backend::Flatpak,
id: "org.mozilla.firefox".into(),
version: None,
description: None,
installed: false,
dependencies: Vec::new(),
reverse_dependencies: Vec::new(),
size: None,
provenance: "flathub".into(),
permissions: Vec::new(),
notes: Vec::new(),
},
],
ambiguous: true,
notes: Vec::new(),
};
assert!(report.ambiguous());
assert!(report.render().contains("ambiguous"));
}
}

View file

@ -6,6 +6,7 @@
pub mod action; pub mod action;
pub mod boot; pub mod boot;
pub mod brand; pub mod brand;
pub mod catalog;
pub mod config; pub mod config;
pub mod disk; pub mod disk;
pub mod effects; pub mod effects;

View file

@ -191,6 +191,70 @@ pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Resul
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 {
SystemAction::Depclean => {
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 = ResolvedPlan::default();
plan.established = true;
plan.consequences.push(format!(
"depclean would remove:\n{}",
out.stdout_lossy().trim()
));
plan.recompute_digest();
return Ok(plan);
}
SystemAction::ApplyUpdates { 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);
}
_ => {}
}
let Some(args) = pretend_args(action) else { let Some(args) = pretend_args(action) else {
return Ok(ResolvedPlan::default()); return Ok(ResolvedPlan::default());
}; };
@ -315,6 +379,57 @@ pub fn execute_plan(
outcome outcome
} }
/// Update the whole Portage world, then rebuild the NVIDIA out-of-tree modules
/// and the initramfs when the driver is installed. Shared by `update_system`
/// and `apply_updates` so both paths stay coherent.
pub(crate) fn portage_world_update(exec: &Exec, root: &Path) -> Result<()> {
run_in_target(
exec,
root,
"sys",
"update system",
"emerge",
&[
"--update".into(),
"--deep".into(),
"--newuse".into(),
"--".into(),
"@world".into(),
],
)?;
// A system with the NVIDIA out-of-tree driver must rebuild its modules
// against any newly installed kernel and regenerate the initramfs, so
// modules, userspace libraries and the boot image stay coherent before the
// next reboot. The record is written by the installer (or by the installed
// system's driver setup).
if root.join("etc/phoebus/nvidia").is_file() {
run_in_target(
exec,
root,
"sys",
"rebuild NVIDIA modules",
"emerge",
&["@module-rebuild".into()],
)?;
run_in_target(
exec,
root,
"sys",
"regenerate the initramfs",
"kernel-install",
&["add-all".into()],
)?;
// Do not report success unless the rebuilt modules exist for a kernel;
// an update that installed a kernel but no matching NVIDIA modules must
// fail loudly, not silently boot degraded.
crate::boot::verify_nvidia_modules(root)?;
// The previous kernels and their module trees are left in place, so a
// failed update still has a bootable, coherent generation to fall back
// to.
}
Ok(())
}
pub fn execute( pub fn execute(
exec: &Exec, exec: &Exec,
action: &SystemAction, action: &SystemAction,
@ -466,21 +581,8 @@ pub fn execute(
)?; )?;
format!("removed {atom} (Portage)") format!("removed {atom} (Portage)")
} }
SystemAction::SearchPackages { query } => { SystemAction::SearchPackages { query, backend } => {
let out = capture_in_target( crate::query::search(exec, root, query, *backend).render()
exec,
root,
"sys",
"search packages",
"emerge",
&[
"--search".into(),
"--quiet".into(),
"--".into(),
query.clone(),
],
)?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
} }
SystemAction::FlatpakInstall { app_id } => { SystemAction::FlatpakInstall { app_id } => {
run_in_target( run_in_target(
@ -809,52 +911,27 @@ pub fn execute(
format!("realised Nix development packages: {}", prepared.join(", ")) format!("realised Nix development packages: {}", prepared.join(", "))
} }
SystemAction::UpdateSystem => { SystemAction::UpdateSystem => {
run_in_target( portage_world_update(exec, root)?;
exec,
root,
"sys",
"update system",
"emerge",
&[
"--update".into(),
"--deep".into(),
"--newuse".into(),
"--".into(),
"@world".into(),
],
)?;
// A system with the NVIDIA out-of-tree driver must rebuild its
// modules against any newly installed kernel and regenerate the
// initramfs, so modules, userspace libraries and the boot image stay
// coherent before the next reboot. The record is written by the
// installer (or by the installed system's driver setup).
if root.join("etc/phoebus/nvidia").is_file() {
run_in_target(
exec,
root,
"sys",
"rebuild NVIDIA modules",
"emerge",
&["@module-rebuild".into()],
)?;
run_in_target(
exec,
root,
"sys",
"regenerate the initramfs",
"kernel-install",
&["add-all".into()],
)?;
// Do not report success unless the rebuilt modules exist for a
// kernel; an update that installed a kernel but no matching
// NVIDIA modules must fail loudly, not silently boot degraded.
crate::boot::verify_nvidia_modules(root)?;
// The previous kernels and their module trees are left in
// place, so a failed update still has a bootable, coherent
// generation to fall back to.
}
"system update complete".to_string() "system update complete".to_string()
} }
SystemAction::CheckUpdates { backend } => {
crate::query::check_updates(exec, root, *backend).render()
}
SystemAction::ApplyUpdates { backend } => {
crate::query::apply_updates(exec, root, *backend)?
}
SystemAction::ListPackages { backend, filter } => {
crate::query::inventory(exec, root, *backend, filter.as_deref()).render()
}
SystemAction::PackageInfo { package, backend } => {
crate::query::package_info(exec, root, package, *backend).render()
}
SystemAction::PackageOwners { path } => crate::query::package_owners(exec, root, path)?,
SystemAction::PackageDependencies { package, reverse } => {
crate::query::package_dependencies(exec, root, package, *reverse)?
}
SystemAction::Depclean => crate::query::depclean(exec, root)?,
SystemAction::CleanCache { backend } => crate::query::clean_cache(exec, root, *backend)?,
SystemAction::CreateSnapshot { operation } => { SystemAction::CreateSnapshot { operation } => {
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?; let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
let source = root.to_string_lossy().to_string(); let source = root.to_string_lossy().to_string();
@ -1143,6 +1220,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
let exec = make_exec(runner.clone()); let exec = make_exec(runner.clone());
let action = SystemAction::SearchPackages { let action = SystemAction::SearchPackages {
query: "firefox".into(), query: "firefox".into(),
backend: Some(phoebus_core::selection::Backend::PortageSource),
}; };
execute(&exec, &action, None, Path::new(&exec.root)).unwrap(); execute(&exec, &action, None, Path::new(&exec.root)).unwrap();
let recorded = runner.recorded(); let recorded = runner.recorded();
@ -1395,4 +1473,56 @@ Total: 1 package (1 new), Size of downloads: 512 KiB
assert!(outcome.output.contains("Idle")); assert!(outcome.output.contains("Idle"));
assert!(outcome.snapshot.is_none()); assert!(outcome.snapshot.is_none());
} }
#[test]
fn depclean_is_previewed_from_pretend_at_review() {
let runner = RecordingRunner::new();
runner.set_response(
"emerge",
CommandOutput {
status: 0,
success: true,
stdout: b">>> These are the packages that would be unmerged:\n\
app-misc/unused-1.0\n\n0 packages selected\n"
.to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let exec = make_exec(runner);
let plan = resolve_effects(&exec, &SystemAction::Depclean, Path::new("/")).unwrap();
assert!(plan.established);
assert!(plan
.consequences
.iter()
.any(|c| c.contains("depclean would remove")));
assert!(plan.render().contains("depclean would remove"));
}
#[test]
fn portage_apply_updates_previews_the_world_plan() {
let runner = RecordingRunner::new();
runner.set_response(
"emerge",
CommandOutput {
status: 0,
success: true,
stdout: b"Calculating dependencies... done!\n\
[ebuild N ] app-editors/vim-9.1.0\n\nTotal: 1 package\n"
.to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let exec = make_exec(runner);
let action = SystemAction::ApplyUpdates {
backend: Some(phoebus_core::selection::Backend::PortageSource),
};
let plan = resolve_effects(&exec, &action, Path::new("/")).unwrap();
assert!(plan.established);
assert!(plan
.effects
.iter()
.any(|e| e.target == "app-editors/vim-9.1.0"));
}
} }

View file

@ -29,6 +29,7 @@ pub mod personal;
pub mod portage; pub mod portage;
pub mod proactive; pub mod proactive;
pub mod probe; pub mod probe;
pub mod query;
pub mod rollback; pub mod rollback;
pub mod sandbox; pub mod sandbox;
pub mod services; pub mod services;

View file

@ -259,6 +259,62 @@ pub fn gc(exec: &Exec, root: &Path) -> Result<()> {
Ok(()) Ok(())
} }
/// One Nix profile link under the target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NixProfile {
pub name: String,
/// The store path the profile link points at (may be empty for a dangling
/// relative link).
pub target: String,
}
fn collect_profile_links(dir: &Path, entries: &mut Vec<NixProfile>) {
let Ok(read) = std::fs::read_dir(dir) else {
return;
};
for entry in read.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with('.') {
continue;
}
let path = entry.path();
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
// `per-user/<user>/` nesting.
collect_profile_links(&path, entries);
continue;
}
if name == "profile" || name.starts_with("profile-") {
let target = std::fs::read_link(&path)
.map(|t| t.to_string_lossy().to_string())
.unwrap_or_default();
entries.push(NixProfile { name, target });
}
}
}
/// Installed Nix profiles (the default profile and per-user generations).
///
/// This deliberately does **not** enumerate the store: a store path is a
/// realised dependency, not an installed program. `store_path_count` reports
/// that separately so the two scopes are never conflated.
pub fn profiles(root: &Path) -> Vec<NixProfile> {
let mut out = Vec::new();
collect_profile_links(&target_path(root, "nix/var/nix/profiles"), &mut out);
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
/// Number of realised store paths, if the store exists. `None` means the store
/// is absent (Nix is not installed).
pub fn store_path_count(root: &Path) -> Option<usize> {
let read = std::fs::read_dir(target_path(root, "nix/store")).ok()?;
Some(
read.flatten()
.filter(|e| e.file_name().to_string_lossy().contains('-'))
.count(),
)
}
/// Realise a bounded set of development packages so they are available offline. /// Realise a bounded set of development packages so they are available offline.
/// ///
/// Each entry is a bare nixpkgs attribute name (`nodejs`, `python312`); URLs and /// Each entry is a bare nixpkgs attribute name (`nodejs`, `python312`); URLs and

View file

@ -43,10 +43,72 @@ pub fn write_config(exec: &Exec, config: &InstallConfig, hardware: &HardwareRepo
keywords.push_str(&sysgen::accept_keywords_mango()); keywords.push_str(&sysgen::accept_keywords_mango());
} }
root.write("etc/portage/package.accept_keywords/phoebus", keywords)?; root.write("etc/portage/package.accept_keywords/phoebus", keywords)?;
normalize_config_permissions(root.path());
exec.logger.info("wrote Portage configuration"); exec.logger.info("wrote Portage configuration");
Ok(()) Ok(())
} }
/// Make the Portage configuration readable by normal users so the read-only
/// `sys` catalogue queries (`emerge --search`, `emerge --pretend`, `equery`,
/// `emerge --depclean --pretend`) work without elevation.
///
/// The configuration contains no secrets (the public Gentoo tree, the GURU
/// overlay and the official binhost); passphrases and keys live elsewhere.
/// Portage can create `repos.conf` with a restrictive mode, so this is applied
/// both when the config is written and again at finalize after all Portage
/// activity.
pub fn normalize_config_permissions(root: &Path) {
use std::os::unix::fs::PermissionsExt;
let chmod = |path: &Path, mode: u32| {
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
};
// Only regular files are touched; symlinks (`make.profile`) and the
// directory holding signing keys (`gnupg/`) are left exactly as they are.
let regular_files = |dir: &Path| -> Vec<std::path::PathBuf> {
std::fs::read_dir(dir)
.map(|read| {
read.flatten()
.filter(|e| {
e.file_type()
.map(|t| t.is_file() && !t.is_symlink())
.unwrap_or(false)
})
.map(|e| e.path())
.collect()
})
.unwrap_or_default()
};
let base = root.join("etc/portage");
if !base.is_dir() {
return;
}
chmod(&base, 0o755);
for file in regular_files(&base) {
chmod(&file, 0o644);
}
// Non-secret configuration directories. `gnupg/` is deliberately excluded:
// it holds signing keys and must stay private.
for name in [
"repos.conf",
"binrepos.conf",
"package.use",
"package.mask",
"package.accept_keywords",
"package.license",
"package.env",
"profile",
] {
let dir = base.join(name);
if dir.is_dir() {
chmod(&dir, 0o755);
for file in regular_files(&dir) {
chmod(&file, 0o644);
}
}
}
}
/// The packages that must be present before the GURU overlay (git-only) can be /// The packages that must be present before the GURU overlay (git-only) can be
/// synced. `dev-vcs/git` is installed from the main tree first. /// synced. `dev-vcs/git` is installed from the main tree first.
pub fn guru_bootstrap_packages() -> Vec<&'static str> { pub fn guru_bootstrap_packages() -> Vec<&'static str> {
@ -395,6 +457,151 @@ pub fn target_root(exec: &Exec) -> TargetRoot {
exec.target() exec.target()
} }
/// One installed Portage package read from the target's VDB.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstalledPortage {
pub atom: String,
pub version: String,
pub size_bytes: Option<u64>,
pub repository: Option<String>,
pub depend: Option<String>,
pub rdepend: Option<String>,
}
/// Split `category/pkgname-1.2.3-r1` into `(category/pkgname, "1.2.3-r1")`.
fn split_pkgver(dirname: &str) -> Option<(String, String)> {
let idx = dirname
.char_indices()
.filter(|(i, c)| *c == '-' && dirname[i + 1..].starts_with(|d: char| d.is_ascii_digit()))
.map(|(i, _)| i)
.next_back()?;
let (package, version) = dirname.split_at(idx);
let version = version.trim_start_matches('-');
if package.is_empty() || version.is_empty() {
None
} else {
Some((package.to_string(), version.to_string()))
}
}
fn read_vdb_field(dir: &Path, name: &str) -> Option<String> {
let text = std::fs::read_to_string(dir.join(name)).ok()?;
let text = text.trim();
if text.is_empty() {
None
} else {
Some(text.to_string())
}
}
/// Read every installed package from the target's Portage VDB. The VDB is the
/// authoritative installed-package record; custom-overlay packages appear here
/// too, which is why there is no separate custom-ebuild inventory.
pub fn installed_packages(root: &Path) -> Vec<InstalledPortage> {
let vdb = root.join("var/db/pkg");
let mut out = Vec::new();
let Ok(categories) = std::fs::read_dir(&vdb) else {
return out;
};
for category in categories.flatten() {
if !category.file_type().map(|t| t.is_dir()).unwrap_or(false) {
continue;
}
let category_name = category.file_name().to_string_lossy().to_string();
// Skip Portage bookkeeping entries.
if category_name.starts_with('.') {
continue;
}
let Ok(packages) = std::fs::read_dir(category.path()) else {
continue;
};
for package in packages.flatten() {
if !package.file_type().map(|t| t.is_dir()).unwrap_or(false) {
continue;
}
let dirname = package.file_name().to_string_lossy().to_string();
let Some((pkgname, version)) = split_pkgver(&dirname) else {
continue;
};
let dir = package.path();
let size_bytes = read_vdb_field(&dir, "SIZE").and_then(|s| s.parse::<u64>().ok());
out.push(InstalledPortage {
atom: format!("{category_name}/{pkgname}"),
version,
size_bytes,
repository: read_vdb_field(&dir, "repository"),
depend: read_vdb_field(&dir, "DEPEND"),
rdepend: read_vdb_field(&dir, "RDEPEND"),
});
}
}
out.sort_by(|a, b| a.atom.cmp(&b.atom).then(a.version.cmp(&b.version)));
out
}
/// One package from `emerge --search`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortageSearchHit {
pub atom: String,
pub version_available: Option<String>,
pub version_installed: Option<String>,
pub description: Option<String>,
pub size: Option<String>,
}
/// Parse the human-readable `emerge --search` output. The format is
/// block-structured; anything that does not match a known field is ignored
/// rather than guessed.
pub fn parse_search(text: &str) -> Vec<PortageSearchHit> {
let mut hits: Vec<PortageSearchHit> = Vec::new();
for line in text.lines() {
let trimmed = line.trim_end();
// A package header looks like `* category/pkgname` or `* category/pkg`.
let header = trimmed.trim_start();
if let Some(rest) = header.strip_prefix('*') {
let rest = rest.trim();
if rest.contains('/') && !rest.contains(' ') {
hits.push(PortageSearchHit {
atom: rest.to_string(),
version_available: None,
version_installed: None,
description: None,
size: None,
});
continue;
}
}
let Some(hit) = hits.last_mut() else {
continue;
};
let content = trimmed.trim_start();
if let Some(value) = content.strip_prefix("Latest version available:") {
hit.version_available = nonempty(value);
} else if let Some(value) = content.strip_prefix("Latest version installed:") {
let value = value.trim();
hit.version_installed = if value.is_empty() || value.contains("Not Installed") {
None
} else {
Some(value.to_string())
};
} else if let Some(value) = content.strip_prefix("Description:") {
hit.description = nonempty(value);
} else if let Some(value) = content.strip_prefix("Size of files:") {
hit.size = nonempty(value);
}
}
hits
}
fn nonempty(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
None
} else {
Some(value.to_string())
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -533,4 +740,106 @@ mod tests {
.unwrap(); .unwrap();
assert!(spec.args.iter().any(|a| a == "--getbinpkg")); assert!(spec.args.iter().any(|a| a == "--getbinpkg"));
} }
#[test]
fn parses_emerge_search_blocks() {
let text = "\
* www-client/firefox
Latest version available: 128.0
Latest version installed: 127.0
Size of files: 512000 KiB
Homepage: https://mozilla.org
Description: Firefox Web Browser
License: MPL-2.0
* www-client/firefox-bin
Latest version available: 128.0
Latest version installed: [ Not Installed ]
Description: Firefox Web Browser (binary)
";
let hits = parse_search(text);
assert_eq!(hits.len(), 2);
assert_eq!(hits[0].atom, "www-client/firefox");
assert_eq!(hits[0].version_available.as_deref(), Some("128.0"));
assert_eq!(hits[0].version_installed.as_deref(), Some("127.0"));
assert_eq!(hits[0].description.as_deref(), Some("Firefox Web Browser"));
assert_eq!(hits[1].atom, "www-client/firefox-bin");
assert_eq!(hits[1].version_installed, None);
}
#[test]
fn reads_the_vdb_for_installed_packages() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let root = Path::new(&exec.root);
let dir = root.join("var/db/pkg/app-editors/vim-9.1.0");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("SIZE"), "4096").unwrap();
std::fs::write(dir.join("repository"), "gentoo").unwrap();
std::fs::write(dir.join("RDEPEND"), "app-editors/vim-core").unwrap();
// A directory that does not parse as pkg-version is skipped.
std::fs::create_dir_all(root.join("var/db/pkg/app-editors/not-a-version")).unwrap();
let installed = installed_packages(root);
assert_eq!(installed.len(), 1);
assert_eq!(installed[0].atom, "app-editors/vim");
assert_eq!(installed[0].version, "9.1.0");
assert_eq!(installed[0].size_bytes, Some(4096));
assert_eq!(installed[0].repository.as_deref(), Some("gentoo"));
assert_eq!(
installed[0].rdepend.as_deref(),
Some("app-editors/vim-core")
);
}
#[test]
fn missing_vdb_is_empty_not_an_error() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
assert!(installed_packages(Path::new(&exec.root)).is_empty());
}
#[test]
fn normalize_config_permissions_makes_read_only_queries_possible() {
use std::os::unix::fs::PermissionsExt;
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let root = Path::new(&exec.root);
let repo_dir = root.join("etc/portage/repos.conf");
std::fs::create_dir_all(&repo_dir).unwrap();
let conf = repo_dir.join("gentoo.conf");
std::fs::write(&conf, "[DEFAULT]\n").unwrap();
let make_conf = root.join("etc/portage/make.conf");
std::fs::write(&make_conf, "COMMON_FLAGS=\"-O2\"\n").unwrap();
let use_dir = root.join("etc/portage/package.use");
std::fs::create_dir_all(&use_dir).unwrap();
let use_file = use_dir.join("phoebus");
std::fs::write(&use_file, "app-misc/hello\n").unwrap();
// Signing keys must never be exposed by the normalisation.
let gnupg = root.join("etc/portage/gnupg");
std::fs::create_dir_all(&gnupg).unwrap();
let pass = gnupg.join("pass");
std::fs::write(&pass, "secret").unwrap();
std::fs::set_permissions(&gnupg, std::fs::Permissions::from_mode(0o700)).unwrap();
std::fs::set_permissions(&pass, std::fs::Permissions::from_mode(0o600)).unwrap();
// Simulate the restrictive modes Portage can leave behind.
std::fs::set_permissions(&repo_dir, std::fs::Permissions::from_mode(0o700)).unwrap();
std::fs::set_permissions(&conf, std::fs::Permissions::from_mode(0o600)).unwrap();
std::fs::set_permissions(&make_conf, std::fs::Permissions::from_mode(0o600)).unwrap();
std::fs::set_permissions(&use_file, std::fs::Permissions::from_mode(0o600)).unwrap();
normalize_config_permissions(root);
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&repo_dir), 0o755, "repos.conf must be searchable");
assert_eq!(mode(&conf), 0o644, "repos.conf entries must be readable");
assert_eq!(mode(&make_conf), 0o644, "make.conf must be readable");
assert_eq!(
mode(&use_file),
0o644,
"package.use entries must be readable"
);
assert_eq!(mode(&gnupg), 0o700, "the keyring directory stays private");
assert_eq!(mode(&pass), 0o600, "the keyring pass file stays private");
}
} }

File diff suppressed because it is too large Load diff

View file

@ -476,7 +476,7 @@ pub fn handle_request(
// 4. General natural language request via the connected model. // 4. General natural language request via the connected model.
let response = with_bridge_ai(exec, root, |ai, facts| { let response = with_bridge_ai(exec, root, |ai, facts| {
service::plan_general(plans, exec, root, &query, facts, ai) service::plan_general(plans, exec, root, &query, facts, ai, constrained_backend)
}); });
match response { match response {
Ok(Ok(plan)) => { Ok(Ok(plan)) => {

View file

@ -30,6 +30,21 @@ use phoebus_installer::service::{self, PreparedPlan};
name = "sys", name = "sys",
about = "Phoebus system interface", about = "Phoebus system interface",
version, version,
after_help = "AI is the default interface. Add --legacy for deterministic, offline \
administration that never contacts a model.\n\n\
Examples (AI default -> deterministic equivalent):\n \
sys search chrome -> sys search chrome --legacy\n \
sys list -> sys list --legacy\n \
sys info firefox -> sys info firefox --legacy\n \
sys updates -> sys updates --legacy\n \
sys install firefox -> sys install firefox --legacy --portage\n \
sys remove firefox -> sys remove firefox --legacy\n \
sys apply updates -> sys apply updates --legacy\n \
sys depclean -> sys depclean --legacy\n \
sys clean cache --nix -> sys clean cache --nix --legacy\n \
sys who owns /usr/bin/vim -> sys who owns /usr/bin/vim --legacy\n\n\
A source flag (--portage/--flatpak/--nix/--snap/--appimage/--ebuild) constrains \
the workflow; it never bypasses the model without --legacy.",
group(clap::ArgGroup::new("backend").args([ group(clap::ArgGroup::new("backend").args([
"portage", "flatpak", "nix", "snap", "appimage", "ebuild" "portage", "flatpak", "nix", "snap", "appimage", "ebuild"
]).multiple(false)) ]).multiple(false))
@ -326,25 +341,25 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
let plan = service::plan_removal(&plans, &exec, &cli.root, &application, backend)?; let plan = service::plan_removal(&plans, &exec, &cli.root, &application, backend)?;
return render_and_execute_plan(&cli, &exec, &plans, plan); return render_and_execute_plan(&cli, &exec, &plans, plan);
} }
if backend.is_some() {
return Err(
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
`sys install <application>` or `sys remove <application>`"
.into(),
);
}
if full_phrase.trim().is_empty() { if full_phrase.trim().is_empty() {
return Err("usage: sys <instruction> --legacy".into()); return Err("usage: sys <instruction> --legacy".into());
} }
return match parse_natural(&full_phrase) { return match parse_natural(&full_phrase) {
Some(action) => execute_action(&cli, &exec, action), Some(action) => {
let action = apply_backend_filter(action, backend)?;
execute_action(&cli, &exec, action)
}
None => { None => {
eprintln!("sys: could not parse `{full_phrase}` in legacy mode."); eprintln!("sys: could not parse `{full_phrase}` in legacy mode.");
eprintln!( eprintln!(
"Legacy mode grammar: sys install <app> --legacy --<source> | \ "Legacy mode grammar: sys install <app> --legacy --<source> | \
sys remove <app> --legacy [--<source>] | \ sys remove <app> --legacy [--<source>] | \
sys history --legacy | sys undo --legacy | sys enable <service> --legacy | \ sys search <query> --legacy [--<source>] | \
sys disable <service> --legacy | sys choose <app> --legacy" sys list --legacy [--<source>] [filter] | \
sys info <package> --legacy [--<source>] | \
sys updates --legacy [--<source>] | sys history --legacy | \
sys undo --legacy | sys enable <service> --legacy | \
sys choose <app> --legacy"
); );
Err("unsupported instruction in legacy mode".into()) Err("unsupported instruction in legacy mode".into())
} }
@ -386,16 +401,53 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
return run_remove(&cli, &exec, &plans, &application, backend); return run_remove(&cli, &exec, &plans, &application, backend);
} }
if backend.is_some() { // Other natural language instructions enter the AI workflow by default.
return Err( // An explicit source flag constrains the workflow; it never bypasses it.
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ run_ask(&cli, &exec, &plans, &full_phrase, backend)
`sys install <application>` or `sys remove <application>`" }
.into(),
);
}
// Other natural language instructions enter the AI workflow by default /// Overlay an explicit source flag onto a deterministic legacy action. Only
run_ask(&cli, &exec, &plans, &full_phrase, None) /// commands whose source can be selected accept a flag; anything else is
/// refused, so a flag can never silently change an unrelated command.
fn apply_backend_filter(
action: SystemAction,
backend: Option<Backend>,
) -> std::result::Result<SystemAction, Box<dyn std::error::Error>> {
let Some(backend) = backend else {
return Ok(action);
};
Ok(match action {
SystemAction::SearchPackages { query, .. } => SystemAction::SearchPackages {
query,
backend: Some(backend),
},
SystemAction::ListPackages { filter, .. } => SystemAction::ListPackages {
backend: Some(backend),
filter,
},
SystemAction::PackageInfo { package, .. } => SystemAction::PackageInfo {
package,
backend: Some(backend),
},
SystemAction::CheckUpdates { .. } => SystemAction::CheckUpdates {
backend: Some(backend),
},
SystemAction::ApplyUpdates { .. } => SystemAction::ApplyUpdates {
backend: Some(backend),
},
SystemAction::CleanCache { .. } => SystemAction::CleanCache {
backend: Some(backend),
},
other => {
return Err(format!(
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
install, remove, search, list, info, updates and cache cleanup, not \
`{}`",
other.describe()
)
.into());
}
})
} }
fn execute_action( fn execute_action(
@ -405,8 +457,18 @@ fn execute_action(
) -> std::result::Result<(), Box<dyn std::error::Error>> { ) -> std::result::Result<(), Box<dyn std::error::Error>> {
println!("{}", actions::preview(&action)); println!("{}", actions::preview(&action));
// Only genuinely privileged actions require root. A personal package
// preference is mutable user state and is written by the invoking account.
// The check runs before effects resolution so an unauthorized invocation
// never causes a command to run.
if action.requires_root() && effective_uid() != 0 {
return Err("mutating actions require root; run `sudo sys ...`".into());
}
let approved = match actions::resolve_effects(exec, &action, &cli.root) { let approved = match actions::resolve_effects(exec, &action, &cli.root) {
Ok(plan) if !plan.effects.is_empty() => { // An established plan is bound to the approval even when it is empty
// (a genuine "0 packages" result), so the review is exact.
Ok(plan) if plan.established => {
println!("{}", plan.render()); println!("{}", plan.render());
Some(plan) Some(plan)
} }
@ -417,12 +479,6 @@ fn execute_action(
} }
}; };
// Only genuinely privileged actions require root. A personal package
// preference is mutable user state and is written by the invoking account.
if action.requires_root() && effective_uid() != 0 {
return Err("mutating actions require root; run `sudo sys ...`".into());
}
let auth: Option<DestructiveAuthorization> = if action.requires_root() { let auth: Option<DestructiveAuthorization> = if action.requires_root() {
let confirmation = SysConfirm { let confirmation = SysConfirm {
action: action.clone(), action: action.clone(),
@ -820,6 +876,12 @@ fn render_and_execute_plan(
) -> std::result::Result<(), Box<dyn std::error::Error>> { ) -> std::result::Result<(), Box<dyn std::error::Error>> {
println!("{}", plan.render()); println!("{}", plan.render());
// A purely informational answer (for example an AI-backed search summary)
// has no actions and must not be sent to the execution boundary.
if plan.actions.is_empty() {
return Ok(());
}
if plan.requires_root && effective_uid() != 0 { if plan.requires_root && effective_uid() != 0 {
return Err("mutating actions require root; run `sudo sys ...`".into()); return Err("mutating actions require root; run `sudo sys ...`".into());
} }
@ -907,16 +969,31 @@ fn resolve_ai(cli: &Cli) -> phoebus_installer::ai_setup::ResolvedAi {
phoebus_installer::ai_setup::resolve(&cli.root, &overrides, conf.as_ref()) phoebus_installer::ai_setup::resolve(&cli.root, &overrides, conf.as_ref())
} }
fn deterministic_fallback(instruction: &str) { fn deterministic_fallback(instruction: &str, backend: Option<Backend>) {
eprintln!("No connected model is available. The deterministic legacy interface still works:"); eprintln!("No connected model is available. The deterministic legacy interface still works:");
match parse_natural(instruction) { match parse_natural(instruction) {
Some(action) => { Some(action) => {
eprintln!(" sys {} --legacy", action.describe()); // Preserve an explicit source constraint in the exact command we
eprintln!("Run it as: sys {} --legacy", instruction.trim()); // suggest, so the user never has to remember it.
let flag = action
.backend()
.or(backend)
.map(|b| format!(" --{}", backend_flag_name(b)))
.unwrap_or_default();
eprintln!(
" sys {} — run it as: sys {} --legacy{flag}",
action.describe(),
instruction.trim()
);
} }
None => { None => {
let flag = backend
.map(|b| format!(" --{}", backend_flag_name(b)))
.unwrap_or_default();
eprintln!( eprintln!(
" Examples: sys enable sshd --legacy | sys install vim --legacy --<source> | \ " Examples: sys enable sshd --legacy | sys install vim --legacy --<source> | \
sys search <query> --legacy{flag} | sys list --legacy{flag} | \
sys info <package> --legacy{flag} | sys updates --legacy{flag} | \
sys history --legacy | sys undo --legacy" sys history --legacy | sys undo --legacy"
); );
eprintln!(" A model only makes this easier; it is never required."); eprintln!(" A model only makes this easier; it is never required.");
@ -972,13 +1049,13 @@ fn run_ask(
let resolved = resolve_ai(cli); let resolved = resolve_ai(cli);
if !resolved.is_configured() { if !resolved.is_configured() {
deterministic_fallback(instruction); deterministic_fallback(instruction, backend);
return Err("no AI provider configured".into()); return Err("no AI provider configured".into());
} }
let transport = match resolved.transport(exec) { let transport = match resolved.transport(exec) {
Ok(t) => t, Ok(t) => t,
Err(e) => { Err(e) => {
deterministic_fallback(instruction); deterministic_fallback(instruction, backend);
return Err(e.to_string().into()); return Err(e.to_string().into());
} }
}; };
@ -1003,11 +1080,12 @@ fn run_ask(
limits: phoebus_ai::install::Limits::default(), limits: phoebus_ai::install::Limits::default(),
}; };
let plan = match service::plan_general(plans, exec, &cli.root, instruction, &facts, &ai) { let plan =
match service::plan_general(plans, exec, &cli.root, instruction, &facts, &ai, backend) {
Ok(plan) => plan, Ok(plan) => plan,
Err(e) => { Err(e) => {
eprintln!("The model is unavailable or returned an unusable plan: {e}"); eprintln!("The model is unavailable or returned an unusable plan: {e}");
deterministic_fallback(instruction); deterministic_fallback(instruction, backend);
return Err("model unavailable".into()); return Err("model unavailable".into());
} }
}; };

View file

@ -439,7 +439,11 @@ impl Installer {
})(); })();
self.exec.umount_chroot()?; self.exec.umount_chroot()?;
result?; result?;
portage::select_profile(&self.exec, &self.config) portage::select_profile(&self.exec, &self.config)?;
// Portage can leave `repos.conf` unreadable to normal users; normalise
// it so read-only `sys` package queries work without elevation.
portage::normalize_config_permissions(std::path::Path::new(&self.exec.root));
Ok(())
} }
fn packages_base(&self) -> Result<()> { fn packages_base(&self) -> Result<()> {
@ -750,6 +754,11 @@ impl Installer {
// earlier stage; a no-op for non-desktop profiles. // earlier stage; a no-op for non-desktop profiles.
desktop::write_session_script(&self.exec, &self.config)?; desktop::write_session_script(&self.exec, &self.config)?;
// 3b. Portage can re-chmod `/etc/portage/repos.conf` during a sync or
// emerge; normalise it last so non-root read-only catalogue queries
// (`sys search/list/info`) work on the installed system.
portage::normalize_config_permissions(std::path::Path::new(&self.exec.root));
// 4. Verify target integrity before snapshotting and unmounting. // 4. Verify target integrity before snapshotting and unmounting.
self.verify_installed_system()?; self.verify_installed_system()?;

View file

@ -15,7 +15,8 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use phoebus_ai::assistant::{complete_plan, AssistantPlan}; use phoebus_ai::assistant::{complete_plan, run_assistant, AssistantPlan};
use phoebus_ai::install::Evidence;
use phoebus_ai::provider::SystemFacts; use phoebus_ai::provider::SystemFacts;
use phoebus_core::action::SystemAction; use phoebus_core::action::SystemAction;
use phoebus_core::effects::{approval_holds, PackageEffect, ResolvedPlan}; use phoebus_core::effects::{approval_holds, PackageEffect, ResolvedPlan};
@ -1122,7 +1123,58 @@ pub fn build_removal_plan(
Ok(plan) Ok(plan)
} }
/// Plan general system administration tasks via connected model. /// Rewrite a lane-selectable catalogue action to an explicit source, and refuse
/// an action that targets a different lane. A spanning action (history,
/// snapshots, services) is returned unchanged.
fn constrain_action(
action: SystemAction,
constraint: Backend,
) -> std::result::Result<SystemAction, String> {
Ok(match action {
SystemAction::SearchPackages { query, .. } => SystemAction::SearchPackages {
query,
backend: Some(constraint),
},
SystemAction::ListPackages { filter, .. } => SystemAction::ListPackages {
backend: Some(constraint),
filter,
},
SystemAction::PackageInfo { package, .. } => SystemAction::PackageInfo {
package,
backend: Some(constraint),
},
SystemAction::CheckUpdates { .. } => SystemAction::CheckUpdates {
backend: Some(constraint),
},
SystemAction::ApplyUpdates { .. } => SystemAction::ApplyUpdates {
backend: Some(constraint),
},
SystemAction::CleanCache { .. } => SystemAction::CleanCache {
backend: Some(constraint),
},
other => {
if let Some(own) = other.backend() {
let matches = own == constraint || (own.is_portage() && constraint.is_portage());
if !matches {
return Err(format!(
"`{}` targets the {} lane, but this request was constrained to {}",
other.describe(),
own.as_str(),
constraint.as_str()
));
}
}
other
}
})
}
/// Plan general system administration tasks via the connected model.
///
/// The model may run a bounded, read-only investigation (search, inventory,
/// information, update checks) before answering. An explicit `constraint`
/// forbids any action that targets a different package lane, so a source flag
/// constrains the AI workflow rather than bypassing it.
pub fn plan_general( pub fn plan_general(
plans: &PlanStore, plans: &PlanStore,
exec: &Exec, exec: &Exec,
@ -1130,16 +1182,67 @@ pub fn plan_general(
query: &str, query: &str,
facts: &SystemFacts, facts: &SystemFacts,
ai: &AiInstall, ai: &AiInstall,
constraint: Option<Backend>,
) -> Result<PreparedPlan> { ) -> Result<PreparedPlan> {
let assistant_plan: AssistantPlan = complete_plan( let instruction = match constraint {
Some(backend) => format!(
"{query}\n\n[source constraint: only the `{}` lane may be used; do not use \
another lane]",
backend.as_str()
),
None => query.to_string(),
};
let investigate = |requests: &[SystemAction]| -> Vec<Evidence> {
requests
.iter()
.map(|request| {
let output = match constraint {
Some(backend) => match constrain_action(request.clone(), backend) {
Ok(action) => match actions::execute(exec, &action, None, root) {
Ok(outcome) => outcome.output,
Err(e) => format!("investigation failed: {e}"),
},
Err(msg) => format!("refused by the source constraint: {msg}"),
},
None => match actions::execute(exec, request, None, root) {
Ok(outcome) => outcome.output,
Err(e) => format!("investigation failed: {e}"),
},
};
Evidence {
request: request.describe(),
output,
}
})
.collect()
};
let assistant_plan: AssistantPlan = run_assistant(
ai.provider, ai.provider,
&ai.endpoint, &ai.endpoint,
&ai.model, &ai.model,
facts, facts,
query, &instruction,
ai.transport, ai.transport,
&investigate,
&ai.limits,
) )
.map_err(|e| ExecError::operation("service", "complete_plan", e.to_string()))?; .map_err(|e| ExecError::operation("service", "run_assistant", e.to_string()))?;
// Apply the source constraint to the final actions too: a lane-specific
// query is rewritten to the constraint, and an action that targets a
// different lane is refused before anything is planned.
let actions_list: Vec<SystemAction> = match constraint {
Some(backend) => assistant_plan
.actions
.iter()
.cloned()
.map(|action| {
constrain_action(action, backend)
.map_err(|msg| ExecError::operation("service", "source constraint", msg))
})
.collect::<Result<Vec<_>>>()?,
None => assistant_plan.actions.clone(),
};
let mut combined_effects = ResolvedPlan { let mut combined_effects = ResolvedPlan {
established: true, established: true,
@ -1148,7 +1251,7 @@ pub fn plan_general(
let mut any_mutating = false; let mut any_mutating = false;
let mut step_effects = Vec::new(); let mut step_effects = Vec::new();
for act in &assistant_plan.actions { for act in &actions_list {
let mut eff = actions::resolve_effects(exec, act, root).map_err(|e| { let mut eff = actions::resolve_effects(exec, act, root).map_err(|e| {
ExecError::operation( ExecError::operation(
"service", "service",
@ -1172,12 +1275,7 @@ pub fn plan_general(
let now = now_unix(); let now = now_unix();
let plan_id = fresh_plan_id("gen"); let plan_id = fresh_plan_id("gen");
let digest = compute_plan_digest( let digest = compute_plan_digest(&actions_list, None, &combined_effects, &step_effects);
&assistant_plan.actions,
None,
&combined_effects,
&step_effects,
);
let rationale_strings: Vec<String> = assistant_plan let rationale_strings: Vec<String> = assistant_plan
.rationale .rationale
.into_iter() .into_iter()
@ -1196,7 +1294,7 @@ pub fn plan_general(
alternatives: Vec::new(), alternatives: Vec::new(),
rationale: rationale_strings, rationale: rationale_strings,
warnings: Vec::new(), warnings: Vec::new(),
actions: assistant_plan.actions, actions: actions_list,
effects: combined_effects, effects: combined_effects,
step_effects, step_effects,
digest, digest,
@ -3816,4 +3914,95 @@ mod tests {
validate_prepared_plan(&exec, root.path(), &plan, Some(&plan.digest), uid) validate_prepared_plan(&exec, root.path(), &plan, Some(&plan.digest), uid)
.expect("a legitimate bound multi-step plan must validate"); .expect("a legitimate bound multi-step plan must validate");
} }
// ------------------------------------------------------------------
// General assistant routing: read-only investigation + source constraint
// ------------------------------------------------------------------
fn general_ai<'a>(transport: &'a dyn phoebus_ai::provider::ModelTransport) -> AiInstall<'a> {
AiInstall {
provider: phoebus_ai::provider::ProviderKind::Local,
endpoint: "http://127.0.0.1:11434/v1/chat/completions".into(),
model: "m".into(),
transport,
limits: phoebus_ai::install::Limits::default(),
}
}
#[test]
fn plan_general_investigates_with_read_only_tools_then_answers() {
use phoebus_ai::provider::{chat_response, ScriptedTransport};
let transport = ScriptedTransport::new(vec![
chat_response(
r#"{"version":1,"kind":"investigate","requests":[{"action":"search_packages","query":"chrome"}]}"#,
),
chat_response(r#"{"version":1,"summary":"Two real candidates found.","actions":[]}"#),
]);
let exec = make_test_exec(Path::new("/"));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let plan = plan_general(
&store,
&exec,
Path::new("/"),
"search chrome",
&SystemFacts::default(),
&general_ai(&transport),
None,
)
.unwrap();
assert!(plan.actions.is_empty(), "an answer has no actions");
assert_eq!(plan.summary, "Two real candidates found.");
assert!(!plan.requires_root, "a read-only answer needs no elevation");
// Two model turns: investigate, then answer.
assert_eq!(transport.requests().len(), 2);
assert!(transport.requests()[1].contains("Package catalogue"));
}
#[test]
fn plan_general_refuses_a_foreign_lane_under_a_constraint() {
use phoebus_ai::provider::{chat_response, ScriptedTransport};
let transport = ScriptedTransport::new(vec![chat_response(
r#"{"version":1,"summary":"list flatpaks","actions":[{"action":"flatpak_list"}],"rationale":[{"action":"flatpak_list","reason":"asked"}]}"#,
)]);
let exec = make_test_exec(Path::new("/"));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let err = plan_general(
&store,
&exec,
Path::new("/"),
"list flatpaks",
&SystemFacts::default(),
&general_ai(&transport),
Some(Backend::PortageSource),
)
.unwrap_err();
assert!(err.to_string().contains("constrained"), "{err}");
}
#[test]
fn plan_general_rewrites_a_laneless_query_to_the_constraint() {
use phoebus_ai::provider::{chat_response, ScriptedTransport};
let transport = ScriptedTransport::new(vec![chat_response(
r#"{"version":1,"summary":"search","actions":[{"action":"search_packages","query":"chrome"}],"rationale":[{"action":"search_packages","reason":"asked"}]}"#,
)]);
let exec = make_test_exec(Path::new("/"));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let plan = plan_general(
&store,
&exec,
Path::new("/"),
"search chrome",
&SystemFacts::default(),
&general_ai(&transport),
Some(Backend::Flatpak),
)
.unwrap();
assert_eq!(
plan.actions,
vec![SystemAction::SearchPackages {
query: "chrome".into(),
backend: Some(Backend::Flatpak),
}]
);
}
} }

View file

@ -648,3 +648,224 @@ fn broker_execute_plan_requires_a_plan_uid() {
.expect("run sys"); .expect("run sys");
assert!(!out.status.success()); assert!(!out.status.success());
} }
// ---------------------------------------------------------------------------
// AI-default routing contract for the catalogue commands
// ---------------------------------------------------------------------------
fn no_model(cmd: &mut Command) -> &mut Command {
cmd.env("PHOEBUS_AI_PROVIDER", "none")
.env("PHOEBUS_AI_API_KEY_FILE", "")
}
#[test]
fn search_without_legacy_enters_the_ai_workflow_and_never_runs_deterministically() {
let root = tempfile::tempdir().expect("temp root");
let out = no_model(&mut sys())
.arg("--root")
.arg(root.path())
.args(["search", "chrome"])
.output()
.expect("run sys");
assert!(!out.status.success());
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("sys search chrome --legacy"),
"must offer the exact legacy alternative: {stderr}"
);
assert!(
!stdout.contains("Package catalogue"),
"the deterministic search must not run without --legacy"
);
assert!(!root
.path()
.join("var/lib/phoebus/transactions.toml")
.exists());
}
#[test]
fn list_info_and_updates_without_legacy_enter_the_ai_workflow() {
for (args, needle) in [
(vec!["list"], "sys list --legacy"),
(vec!["info", "firefox"], "sys info firefox --legacy"),
(vec!["updates"], "sys updates --legacy"),
] {
let root = tempfile::tempdir().expect("temp root");
let out = no_model(&mut sys())
.arg("--root")
.arg(root.path())
.args(&args)
.output()
.expect("run sys");
assert!(!out.status.success(), "expected failure for {args:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains(needle), "{args:?} -> {stderr}");
}
}
#[test]
fn a_source_flag_alone_constrains_the_ai_and_never_bypasses_it() {
let root = tempfile::tempdir().expect("temp root");
let out = no_model(&mut sys())
.arg("--root")
.arg(root.path())
.args(["search", "chrome", "--flatpak"])
.output()
.expect("run sys");
assert!(!out.status.success());
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stdout.contains("Package catalogue"),
"a source flag must not bypass the model"
);
assert!(
stderr.contains("sys search chrome --legacy --flatpak"),
"the deterministic alternative must keep the source flag: {stderr}"
);
}
#[test]
fn legacy_search_is_deterministic_and_never_contacts_a_model() {
let root = tempfile::tempdir().expect("temp root");
let empty = tempfile::tempdir().expect("empty PATH");
// A configured remote provider with a dead endpoint must be ignored under
// --legacy: no network is attempted.
let out = sys()
.env("PATH", empty.path())
.env("PHOEBUS_AI_PROVIDER", "deepseek")
.env("PHOEBUS_AI_ENDPOINT", "http://127.0.0.1:1/never")
.env("PHOEBUS_AI_API_KEY_FILE", "")
.arg("--root")
.arg(root.path())
.args(["search", "chrome", "--legacy"])
.output()
.expect("run sys");
assert!(
out.status.success(),
"stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("Package catalogue for `chrome`"),
"{stdout}"
);
}
#[test]
fn legacy_list_reads_the_vdb_and_is_read_only() {
let root = tempfile::tempdir().expect("temp root");
let empty = tempfile::tempdir().expect("empty PATH");
let dir = root.path().join("var/db/pkg/app-editors/vim-9.1.0");
std::fs::create_dir_all(&dir).expect("vdb dir");
let out = sys()
.env("PATH", empty.path())
.arg("--root")
.arg(root.path())
.args(["list", "--legacy"])
.output()
.expect("run sys");
assert!(
out.status.success(),
"stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("app-editors/vim"), "{stdout}");
assert!(
!root
.path()
.join("var/lib/phoebus/transactions.toml")
.exists(),
"a read-only inventory must not write a transaction"
);
}
#[test]
fn legacy_inventory_honours_a_source_filter() {
let root = tempfile::tempdir().expect("temp root");
let empty = tempfile::tempdir().expect("empty PATH");
std::fs::create_dir_all(root.path().join("var/db/pkg/app-editors/vim-9.1.0")).expect("vdb dir");
let out = sys()
.env("PATH", empty.path())
.arg("--root")
.arg(root.path())
.args(["list", "--legacy", "--flatpak"])
.output()
.expect("run sys");
assert!(out.status.success());
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("[flatpak]"), "{stdout}");
assert!(
!stdout.contains("app-editors/vim"),
"a Flatpak-filtered inventory must not list Portage packages: {stdout}"
);
}
#[test]
fn legacy_updates_check_is_read_only() {
let root = tempfile::tempdir().expect("temp root");
let empty = tempfile::tempdir().expect("empty PATH");
let out = sys()
.env("PATH", empty.path())
.arg("--root")
.arg(root.path())
.args(["updates", "--legacy"])
.output()
.expect("run sys");
assert!(
out.status.success(),
"stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Unified Update Overview"), "{stdout}");
assert!(!root
.path()
.join("var/lib/phoebus/transactions.toml")
.exists());
}
#[test]
fn json_search_without_legacy_or_broker_fails_closed() {
let out = sys()
.args([
"--action",
r#"{"action":"search_packages","query":"chrome"}"#,
])
.output()
.expect("run sys");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("--legacy") || stderr.contains("--broker"),
"{stderr}"
);
}
#[test]
fn mutating_catalogue_maintenance_requires_root() {
if effective_uid_is_root() {
return;
}
let root = tempfile::tempdir().expect("temp root");
for args in [
vec!["depclean", "--legacy"],
vec!["apply", "updates", "--legacy"],
vec!["clean", "cache", "--legacy"],
] {
let out = sys()
.arg("--root")
.arg(root.path())
.args(&args)
.output()
.expect("run sys");
assert!(!out.status.success(), "expected refusal for {args:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("require root"), "{args:?} -> {stderr}");
}
}

View file

@ -46,6 +46,16 @@ run_expect_nonzero() {
fi fi
} }
# run_expect_zero_contains <id> <needle> <args...>
run_expect_zero_contains() {
local id="$1" needle="$2"; shift 2
if "$SYS" "$@" >"$WORK/$id.out" 2>"$WORK/$id.err" && grep -q -- "$needle" "$WORK/$id.out"; then
report "$id" PASS "$(head -c 160 "$WORK/$id.out" | tr '\n' ' ')"
else
report "$id" FAIL "rc=$? expected 0 and '$needle' in stdout"
fi
}
# json_nonzero <id> <needle> <json> # json_nonzero <id> <needle> <json>
json_nonzero() { json_nonzero() {
local id="$1" needle="$2" json="$3" local id="$1" needle="$2" json="$3"
@ -150,6 +160,41 @@ else
report investigate-check-backend FAIL "$(head -c 160 "$WORK/be.err")" report investigate-check-backend FAIL "$(head -c 160 "$WORK/be.err")"
fi fi
# --- Package catalogue (read-only, --legacy) ------------------------------
run_expect_zero_contains search-legacy "Package catalogue" --legacy search firefox
run_expect_zero_contains list-legacy "Package catalogue" --legacy list
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 json-search-legacy "Package catalogue" --legacy --action '{"action":"search_packages","query":"firefox"}'
# A recognizable catalogue command without --legacy must enter the AI workflow
# and must not run deterministically when no model is available.
if ! PHOEBUS_AI_PROVIDER="" PHOEBUS_AI_BACKEND=direct \
"$SYS" search firefox >"$WORK/srch-noai.out" 2>"$WORK/srch-noai.err" && \
grep -q "sys search firefox --legacy" "$WORK/srch-noai.err" && \
! grep -q "Package catalogue" "$WORK/srch-noai.out"; then
report search-no-model-offer PASS "offered the exact legacy alternative"
else
report search-no-model-offer FAIL "$(head -c 200 "$WORK/srch-noai.err")"
fi
# A source flag alone constrains the AI; it never bypasses it.
if ! PHOEBUS_AI_PROVIDER="" PHOEBUS_AI_BACKEND=direct \
"$SYS" search firefox --flatpak >"$WORK/srch-flag.out" 2>"$WORK/srch-flag.err" && \
grep -q "sys search firefox --legacy --flatpak" "$WORK/srch-flag.err" && \
! grep -q "Package catalogue" "$WORK/srch-flag.out"; then
report search-flag-constraint PASS "source flag constrained the AI workflow"
else
report search-flag-constraint FAIL "$(head -c 200 "$WORK/srch-flag.err")"
fi
# Destructive maintenance is privileged.
if [[ "$(id -u)" -ne 0 ]]; then
run_expect_nonzero nonroot-depclean "require root" --legacy depclean
run_expect_nonzero nonroot-apply-updates "require root" apply updates --legacy
run_expect_nonzero nonroot-clean-cache "require root" clean cache --legacy
fi
# --- Optional mutating group (disposable VM only) ------------------------- # --- Optional mutating group (disposable VM only) -------------------------
if [[ "$MUTATE" == "1" ]]; then if [[ "$MUTATE" == "1" ]]; then
PKG="${SYS_ACCEPTANCE_PACKAGE:-app-misc/hello}" PKG="${SYS_ACCEPTANCE_PACKAGE:-app-misc/hello}"