Compare commits

...

5 commits

Author SHA1 Message Date
3435d5aed1 docs: record the VM-verified install journey
Some checks are pending
ci / test (push) Waiting to run
Record the disposable-VM evidence for the AI-first install workflow: the
deterministic install, the explicit --portage install/remove journey with a
protective snapshot and durable history, the no-model offer, the read-only
investigation actions, and the 19/19 acceptance matrix. Note the AI-selected
journey as the remaining gate (needs a connected provider).
2026-09-23 21:42:11 -07:00
dedaa4bc48 fix: defects found by the VM install journey
- chooser: keep the plain Portage install atom and record the version
  separately. emerge rejects a bare versioned atom (app-misc/hello-2.12.3), so
  resolve/split now produce app-misc/hello + version 2.12.3.
- effects: parse emerge --unmerge --pretend output (it does not use the
  [ebuild] form), so sys remove has a concrete plan instead of being refused as
  unestablished.
- action: reject unknown fields on internally tagged unit variants
  (deny_unknown_fields does not cover them), closing a fail-closed gap.
- transaction: fsync the log so a completed outcome survives power loss and is
  not later read as an interrupted operation.
- serial-driver: import re at module level (do_boot used it unqualified).
2026-09-23 21:40:42 -07:00
b4729e443d test(install): verify the explicit Portage plan end to end
Add an executor test: resolve an explicit --portage plan, confirm verification
fails before the merge and succeeds once the VDB entry exists, so success is
never claimed from a zero exit alone.
2026-09-23 20:32:24 -07:00
4934b4c221 test(vm): run the deterministic install with the --no-ai break-glass
The install harness drives the deterministic backend, which must pass the
documented --no-ai break-glass to satisfy the mandatory-AI install gate. The
previous invocation omitted it and the installer correctly refused.
2026-09-23 20:31:07 -07:00
f9e39925b4 feat(install): AI-first sys install workflow
Implement the shared installation workflow (ADR 0013). sys install, sys ask
install and the explicit backend flags all use one path: identify -> evidence
-> AI investigation -> deterministic validation/effects -> review -> approval
-> execute -> verify -> history.

- phoebus-ai::install: bounded, multi-turn investigation. The model may request
  typed read-only evidence (discover_candidates, inspect_candidate,
  check_backend, inspect_installation), ask one bounded question about intent,
  and must return a structured InstallProposal. Turn/request/size limits and
  repeated-request detection bound it; a rejected proposal is revised.
- phoebus-core: add the four read-only investigation actions and strict
  validators; add a transaction id; backend/kind wire names now match as_str.
- phoebus-executor::install: resolve_explicit (no model, no fallback),
  resolve_deterministic and resolve_with_ai; validate_proposal re-resolves the
  candidate against real metadata, rejects fabrication/ambiguity/staleness/
  duplicates, maps it to the existing broker action, and binds approval to a
  digest; revalidate + verify_installed. chooser gains per-lane friendly-name
  resolution and structured evidence.
- transaction::begin/finish record an in-progress transaction before mutation.
- sys: --portage/--flatpak/--nix/--snap/--appimage/--ebuild (mutually
  exclusive) bypass the model; an unqualified install consults the model and,
  with none, prints the deterministic selection and installs nothing.
- The installer persists /etc/phoebus/install.toml; sys loads it and adds free
  space, Wayland, usable lanes, saved preferences and recovery capability to
  the bounded facts.
- Docs: ADR 0013, docs/SYS.md install sections and cases 23-31, CHANGELOG,
  STATUS, HANDOFF, ROADMAP. New live-VM workflow check script.

Host gates pass: fmt, clippy (no new warnings), workspace tests, make test.
VM: verified the workflow CLI and read-only investigation on the reference
LiveGUI ISO; a full target install journey is running (see HANDOFF).
2026-09-23 20:30:13 -07:00
26 changed files with 3840 additions and 101 deletions

View file

@ -3,6 +3,65 @@
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-24 — AI-first package installation
- **Shared installation workflow (`phoebus-executor::install`, ADR 0013):**
`sys install <application>`, `sys ask install <application>` and the explicit
backend flags all run one flow: identify → evidence → AI investigation →
deterministic validation + effects → review → approval → execute → verify →
history. The AI only recommends; the resolver re-checks every proposal
against real backend metadata and maps it to the existing broker action.
- **Bounded investigation (`phoebus-ai::install`):** the model may request
typed, read-only evidence (`discover_candidates`, `inspect_candidate`,
`check_backend`, `inspect_installation`) and ask one bounded question about
intent before proposing a structured `InstallProposal`. Bounds: turn,
per-turn request and evidence-size limits plus repeated-request detection. A
rejected proposal is fed back for a bounded revision.
- **Friendly-name resolution and validation:** per-lane resolution
(`chooser::resolve_for_backend`) maps friendly names to real identifiers,
reports ambiguity, and never fabricates a candidate. Duplicate installs,
stale versions and changed effects are refused; approval is bound to a digest
and revalidated before execution.
- **Explicit backend flags are authoritative:** `--portage`, `--flatpak`,
`--nix`, `--snap`, `--appimage`, `--ebuild` bypass the model, are mutually
exclusive, and never fall back to another lane.
- **No-model path:** an unqualified install with no provider prints the
deterministic selection and the explicit commands and installs nothing;
provider failure is never permission to install.
- **Install facts are real:** `sys` now loads the installed
`/etc/phoebus/install.toml` instead of assuming defaults, and the bounded
facts include free space, Wayland, the usable lanes, saved preferences and
recovery capability.
- **Transaction engine:** installs record an in-progress transaction before the
mutation (`transaction::begin`/`finish`), verify installed identity/version
afterwards, and record failures truthfully.
- **ADRs/docs:** new `docs/adr/0013-ai-first-installation.md`; `docs/SYS.md`
updated with the install workflow and acceptance cases 23–31.
### Verified (host)
- `cargo fmt`, `cargo clippy --workspace --all-targets` (no new warnings) and
`cargo test --workspace` pass. New tests cover: the AI loop (steps, bounds,
repetition, revision, provider failure), resolver fabrication/ambiguity/
duplicate/changed-evidence, action mapping, transaction begin/finish, CLI
flag conflicts/no-fallback/no-model, and target-vs-host facts.
### Verified (disposable VM)
- A deterministic minimal install completed (`INSTALL-RC=0`), including
installing `/usr/local/bin/sys` and verifying the target, then booted detached
(systemd `running`, 0 failed units).
- `sys install app-misc/hello --portage` ran the full workflow: plan + effects,
protective snapshot, install, verification in the package database, and a
durable transaction in `sys history` that survived a clean reboot.
- `sys remove app-misc/hello`, the no-model offer, backend-flag conflicts and
the read-only investigation actions were exercised; the matrix reported
`FAIL=0` (19/19).
### Not yet verified
- The **AI-selected** journey (`sys install <app>` with a connected model) is
unit-tested with scripted transports and was not run against a live provider:
no authorised provider/credential exists in this environment. The exact
command is in `docs/HANDOFF.md`; it is the remaining gate.
## 2026-09-24 — Hardware-aware software selection, Snap/AppImage/custom ebuild, `sys` lifecycle ## 2026-09-24 — Hardware-aware software selection, Snap/AppImage/custom ebuild, `sys` lifecycle
- **Shared selection policy (`phoebus-core::selection`, ADR 0006 revised):** - **Shared selection policy (`phoebus-core::selection`, ADR 0006 revised):**

View file

@ -3,105 +3,110 @@
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-24), hardware-aware software - **Last updated:** this session (2026-09-24), AI-first package installation:
selection across all lanes, Snap/AppImage/custom-ebuild backends, and the the shared `sys install` workflow, bounded AI investigation, deterministic
installed-`sys` lifecycle. proposal validation, explicit backend flags and truthful install transactions.
- **Current focus:** - **Current focus:**
1. **Shared selection policy** (`phoebus-core::selection`, ADR 0006 revised): 1. **Shared install workflow** (`phoebus-executor::install`, ADR 0013):
fixed category routing is gone. A deterministic, inspectable policy identify → evidence → AI investigation → deterministic validation/effects
resolves real candidates from Portage (source/binary/vendor), Nix, Flatpak, → review → approval → execute → verify → history. Used by
Snap, AppImage and the Phoebus overlay; separates hard constraints from `sys install`, `sys ask install ...` and the explicit backend flags.
preferences; keeps base components under Portage; honours and persists 2. **Bounded investigation** (`phoebus-ai::install`): the model may request
explicit choices; errors instead of silently switching lanes; reuses an typed read-only evidence (`discover_candidates`, `inspect_candidate`,
already-installed lane. `check_backend`, `inspect_installation`) and ask one bounded question
2. **New backends** (`phoebus-executor`): `snap` (daemon/confinement before proposing; turn/request/size limits and repeated-request detection
detection, install/list/remove/refresh/connections, `app-containers/snapd` bound it. A rejected proposal is revised with the resolver's finding.
through Portage), `appimage` (pinned-hash acquire/import, ELF arch check 3. **Deterministic authority**: `validate_proposal` re-resolves the candidate
without execution, desktop integration, data-preserving removal), `ebuild` against real metadata (fabrication, staleness, ambiguity and duplicates
(Phoebus overlay, rationale + content digest, approval-gated build with are refused), maps it to the existing broker action, and binds approval to
Portage's sandbox). a digest that is revalidated before execution.
3. **`sys` surface**: `choose_package`, `set_package_preference`, `snap_*`, 4. **Explicit flags**: `--portage/--flatpak/--nix/--snap/--appimage/--ebuild`
`appimage_*`, `custom_ebuild_*` typed actions with strict validators and bypass the model, are mutually exclusive and never fall back.
deterministic phrases; `docs/SYS.md` is the command reference and 5. **No-model path**: an unqualified install with no provider prints the
acceptance matrix. deterministic selection and explicit commands and installs nothing.
4. **`sys` in the installed target**: located beside the installer, copied to 6. **Transactions**: `transaction::begin`/`finish` record an in-progress
`/usr/local/bin/sys`, proven to run in the target chroot before the transaction before the mutation; installs verify identity/version after.
recovery snapshot; install fails closed if absent. 7. **Real install facts**: `/etc/phoebus/install.toml` is now written by the
5. **VM harness**: `install.sh` fetches `sys`; `rollback-guest.sh` uses the installer and read by `sys`; facts add free space, Wayland, usable lanes,
installed binary; new `installer/tests/vm/sys-acceptance.sh`. saved preferences and recovery capability.
- **Last verified (this session):** - **Last verified (this session):**
- `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets` - `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets`
(no new warnings) and `cargo test --workspace` pass. New coverage: the (no new warnings) and `cargo test --workspace` pass.
selection policy (16 tests across hardware/preference/failure cases), Snap - New tests: AI loop steps/bounds/repetition/revision/provider-failure;
and AppImage parsing/behaviour, the ebuild digest/approval path, chooser resolver fabrication/ambiguity/duplicate/changed-version; action mapping;
resolution, and `sys_cli` host tests. transaction begin/finish (ok and failed); `sys_cli` flag conflicts,
- `installer/tests/vm/test_vmsafety.py` (18 tests) passes with the new guest no-fallback, no-model offer, help; target-vs-host facts.
script. - `installer/tests/vm/test_vmsafety.py` (18 tests) passes with the extended
- **Not yet verified this session:** the new lanes and the installed-`sys` `sys-acceptance.sh`.
lifecycle are unit/integration tested but **not exercised in a booted VM**: a - **Disposable VM (deterministic minimal install, `--no-ai`)**: completed
full `gui-install` (started by a prior session) was still running on the only with `INSTALL-RC=0` and installed `/usr/local/bin/sys`; booted detached
disposable disk. The NVIDIA boot gates and the rollback destructive gate remain (systemd `running`). `sys install app-misc/hello --portage` produced a
unrun. plan + effects, a protective snapshot, installed and verified it in the
package database, and recorded a durable transaction that survived a clean
reboot. `sys remove` succeeded (after fixing unmerge parsing) and the
acceptance matrix reported `FAIL=0` (19/19). See
`docs/CHANGELOG.md` and `docs/STATUS.md` for details.
- **Not yet verified this session:** the **AI-selected** journey
(`sys install <app>` with a connected model). It is unit-tested with scripted
transports but was not run against a live provider because no authorised
provider/credential exists in this environment. The exact command is in
"Next actions" below.
- **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. **Boot the installed disk and run the `sys` acceptance matrix** once the 1. **AI-selected install journey (needs an authorised provider)**: boot the
current `gui-install` VM releases the disk: installed disposable disk, serve the built `sys` and a 0600 key file, then:
```sh ```sh
cp installer-rs/target/x86_64-unknown-linux-gnu/release/phoebus-installer \ sudo sys --ai-provider deepseek --ai-api-key-file /run/phoebus/ai.key \
installer-rs/target/x86_64-unknown-linux-gnu/release/sys /home/dominic/vmlab/serve/ install <application>
cp installer/tests/vm/{install.sh,sys-acceptance.sh,rollback-guest.sh,rollback-verify.sh} /home/dominic/vmlab/serve/ # and the no-model control in the same run:
# in the serve dir: python3 -m http.server 8000 --bind 127.0.0.1 PHOEBUS_AI_PROVIDER= sudo sys install <application>
DISK=/var/tmp/phoebus-vm/disks/<clone>.qcow2 OVMF_CODE=... OVMF_VARS=... \
BOOT_CHECKS='test -x /usr/local/bin/sys && /usr/local/bin/sys --version; sudo /usr/local/bin/sys history; \
curl -fsSL http://10.0.2.2:8000/sys-acceptance.sh -o /tmp/sa.sh && SYS_ACCEPTANCE_MUTATE=1 bash /tmp/sa.sh; \
echo ===CHECKS-$(printf END)===' \
python3 installer/tests/vm/serial-driver.py boot
``` ```
Confirm `/usr/local/bin/sys` exists (installed lifecycle), the matrix reports Confirm the model requests evidence, the resolver confirms the candidate,
`FAIL=0`, and a Portage install/remove appears in `sys history`. the plan is presented before approval, and the transaction is recorded. No
2. **Snap / AppImage / custom-ebuild VM journeys**: on a disposable installed credential is available here; do not invent one.
VM, `sys snap install <tiny-snap>`, `sys appimage import` a small test image, 2. **Rerun the deterministic journey on a fresh disk** if the harness changes:
and one `custom_ebuild_prepare` + `custom_ebuild_install`. Needs network for ```sh
Snap/AppImage; the custom-ebuild path can use a local file. make static
3. **Rollback VM acceptance**: clone the installed disk and run cp installer-rs/target/x86_64-unknown-linux-gnu/release/{phoebus-installer,sys} /home/dominic/vmlab/serve/
`serial-driver.py rollback`. The destructive gate is written and unit-checked cp installer/tests/vm/{install.sh,sys-acceptance.sh} /home/dominic/vmlab/serve/
but unrun. OVMF_CODE=/usr/share/OVMF/OVMF_CODE_4M.fd OVMF_VARS=/usr/share/OVMF/OVMF_VARS_4M.fd \
4. **NVIDIA hardware acceptance (BLOCKED)**: needs an NVIDIA GPU; unchanged. DISK=/var/tmp/phoebus-vm/disks/<qcow2> \
5. **Live AI provider call**: exercise `sys ask` with a real 0600 key file; the ISO=/home/dominic/Source/phoebus_os/livegui-amd64-20260913T163055Z.iso \
path is fixture-verified only. KERNEL=/var/tmp/live-boot/gentoo INITRD=/var/tmp/live-boot/gentoo.igz \
6. **Installed Mango desktop** and the **live ISO `gui` journey** remain to be INSTALL_URL=http://10.0.2.2:8000/install.sh \
re-run on this checkout. python3 installer/tests/vm/serial-driver.py install
# then serial-driver.py boot with BOOT_CHECKS running the matrix
```
3. **Rollback VM acceptance** (`serial-driver.py rollback`) remains unrun.
4. **NVIDIA hardware acceptance (BLOCKED)**: needs an NVIDIA GPU.
5. **Installed Mango desktop** and the **live ISO `gui` journey** remain to be
re-run.
## Known blockers / risks ## Known blockers / risks
- **One disposable disk, shared with a long `gui-install`.** Do not start a - **A full VM install still takes hours** (base stage ~116 min). Use the already
second VM against the same qcow2; clone it first. `make doctor` reports installed disposable disk (clone it) for `sys install` journeys rather than a
~29 GiB free now (the earlier ~12 GiB disk blocker has eased). fresh install.
- **No NVIDIA GPU** (and no authorised passthrough): acceleration cannot be - **No NVIDIA GPU** (and no authorised passthrough).
verified here. - **Snap needs network and AppArmor** for meaningful confinement; the lane
- **Snap needs network and AppArmor** for meaningful confinement. The lane detects confinement honestly.
detects confinement honestly; a host without AppArmor reports `none`. - **AppImage provides no sandbox**; do not describe it as one.
- **AppImage provides no sandbox.** Do not describe it as one; runtime - **Custom ebuilds remain separately reviewed, untrusted artifacts**; the
requirements (FUSE) are not auto-installed. install workflow never builds one during investigation.
- **The custom-ebuild build is Portage sandboxed, not VM-isolated.** Treat a - **OpenCode transport** concatenates messages, so multi-turn investigation is
generated ebuild as untrusted and keep the digest-bound approval. best-effort there; the direct providers carry the full conversation.
- **`gui-install` completion is host-time bound** (base stage ~116 min, kernel
compile beyond the 4 h timeout). The deterministic install + detached boot is
the proven path.
- Harness artifacts live under `/var/tmp/phoebus-vm/` (outside git). - Harness artifacts live under `/var/tmp/phoebus-vm/` (outside git).
## Environment notes ## Environment notes
- Dev host: Ubuntu 26.04. QEMU/OVMF/xorriso/rustfmt/clippy/ImageMagick/visudo - Dev host: Ubuntu 26.04. QEMU/OVMF/xorriso/rustfmt/clippy/ImageMagick/visudo
present. `flatpak` and `snap` clients are installed on the host (not usable as present. `flatpak` and `snap` clients are present on the host (not proof of
proof of the VM lanes). the VM lanes).
- Debian-Live base ISO is cached at `/home/dominic/debian-live-standard.iso`. - VM harnesses: `installer/tests/vm/{gui-driver,serial-driver,appliance-driver,live-driver}.py`
- VM harnesses: `installer/tests/vm/gui-driver.py`, `serial-driver.py`, and `sys-acceptance.sh`. `DISK` must be a disposable qcow2; never `/dev/*`.
`appliance-driver.py`, `live-driver.py`, and `sys-acceptance.sh`.
`DISK` must be a disposable qcow2; never point it at `/dev/*`.
- Serve fixtures from `/home/dominic/vmlab/serve` with - Serve fixtures from `/home/dominic/vmlab/serve` with
`python3 -m http.server 8000 --bind 127.0.0.1` (reachable as `10.0.2.2:8000`). `python3 -m http.server 8000 --bind 127.0.0.1` (reachable as `10.0.2.2:8000`).
- The static binaries for the VM: `make static` builds `phoebus-installer` and - The static binaries for the VM: `make static` builds `phoebus-installer` and

View file

@ -25,6 +25,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**.
| — | AI-guided install optimization | Partial | DeepSeek/OpenAI/local providers, evidence-gated typed review, mandatory at install with `--no-ai` break-glass; fixture-verified, no live call | | — | AI-guided install optimization | Partial | DeepSeek/OpenAI/local providers, evidence-gated typed review, mandatory at install with `--no-ai` break-glass; fixture-verified, no live call |
| — | Nix as a built-in second lane | Partial | pinned-release bootstrap; `nix-daemon` active and `nix shell nixpkgs#hello` VM-verified; on by default | | — | Nix as a built-in second lane | Partial | pinned-release bootstrap; `nix-daemon` active and `nix shell nixpkgs#hello` VM-verified; on by default |
| — | Hardware-aware software selection (all lanes) | Partial | shared policy + candidate resolution + `choose_package`/`set_package_preference` (unit-tested); Snap, AppImage and custom-ebuild backends implemented (unit-tested); VM journeys pending (ADR 0006 revised) | | — | Hardware-aware software selection (all lanes) | Partial | shared policy + candidate resolution + `choose_package`/`set_package_preference` (unit-tested); Snap, AppImage and custom-ebuild backends implemented (unit-tested); VM journeys pending (ADR 0006 revised) |
| — | AI-first package installation | Partial | shared `sys install` workflow with bounded AI investigation, deterministic validation, explicit backend flags and no-model offer (unit/integration-tested); VM install journeys pending (ADR 0013) |
| — | Git workflow + agent guide | Done | this `docs/` set, `.githooks/`, `scripts/` | | — | Git workflow + agent guide | Done | this `docs/` set, `.githooks/`, `scripts/` |
## Immediate next steps ## Immediate next steps

View file

@ -92,6 +92,13 @@ still not VM-verified.
| AppImage lane (import/acquire/integrity/desktop/remove) | yes | yes | no | no | | AppImage lane (import/acquire/integrity/desktop/remove) | yes | yes | no | no |
| Custom ebuild overlay (stage/approve/build/remove) | yes | yes | no | no | | Custom ebuild overlay (stage/approve/build/remove) | yes | yes | no | no |
| `sys` installed into the target + verified in chroot | yes | yes (unit) | no | no | | `sys` installed into the target + verified in chroot | yes | yes (unit) | no | no |
| AI-first install workflow (`sys install`, `sys ask`) | yes | yes | explicit-backend journey; AI-selected not run | no |
| Bounded AI investigation (typed read-only evidence) | yes | yes | read-only actions on a booted VM | no |
| Deterministic proposal validation (fabrication/stale/ambiguous/duplicate) | yes | yes | no | no |
| Explicit backend install flags (no fallback) | yes | yes | yes (Portage install + remove, history) | no |
| No-model unqualified install refuses and offers commands | yes | yes | yes (matrix case) | no |
| Install transaction begin/finish + verification | yes | yes | yes (install verified; durable across reboot) | no |
| Installed config loaded (`/etc/phoebus/install.toml`) | yes | no | install writes it; `sys` reads it on the installed system | no |
| `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 |

View file

@ -16,6 +16,63 @@ sys ask "<request>" # assistant proposes the same typed actions
Run `sys --help` for the flags. Mutating actions require root (`sudo sys ...`). Run `sys --help` for the flags. Mutating actions require root (`sudo sys ...`).
Without a model, `sys ask` prints the deterministic equivalent and exits. Without a model, `sys ask` prints the deterministic equivalent and exits.
## AI-first installation (`sys install`)
```
sys install firefox # AI investigates and recommends
sys install firefox --flatpak # deterministic, no model
sys install firefox --portage
sys install nodejs --nix
sys install thunderbird --snap
sys install MyTool --appimage
sys install app-misc/my-thing --ebuild # build a staged custom ebuild
sys ask install firefox # the same workflow via the assistant
```
One shared workflow (ADR 0013) is used by all of these:
```
identify -> evidence -> AI investigation -> proposed selection
-> deterministic validation + effects -> review -> approve -> execute
-> verify -> history
```
- **Unqualified** installation consults the connected model. The model may
request bounded, read-only evidence (`discover_candidates`,
`inspect_candidate`, `check_backend`, `inspect_installation`) and may ask one
bounded question about your intent. It returns a structured proposal naming a
real candidate id; the deterministic resolver independently confirms that
candidate against backend metadata, computes the effects, and binds approval
to a digest. A fabricated, stale, ambiguous or duplicating proposal is
rejected and returned to the model for a bounded revision.
- **Explicit backend flags** (`--portage`, `--flatpak`, `--nix`, `--snap`,
`--appimage`, `--ebuild`) bypass the model, are mutually exclusive, and never
fall back to another lane. If the lane cannot satisfy the request, the reason
and alternatives are shown and nothing is installed.
- **No model** for an unqualified install: the deterministic candidate
selection and the explicit commands are printed, and nothing is installed. A
provider failure is never permission to install through a lane.
- Every install is recorded in the transaction log **before** it runs (an
interrupted run leaves an in-progress record) and verified afterwards
(package database, `flatpak list`, `snap list`, or the managed AppImage
record). A verification failure is a failed transaction.
Read-only investigation is also directly available:
| Phrase / JSON | Typed action | Kind |
| --- | --- | --- |
| *(JSON only)* | `discover_candidates` | read |
| *(JSON only)* | `inspect_candidate` | read |
| *(JSON only)* | `check_backend` | read |
| *(JSON only)* | `inspect_installation` | read |
Example:
```sh
sys --action '{"action":"discover_candidates","query":"firefox","gui":true}'
sys --action '{"action":"check_backend","backend":"snap"}'
```
## Commands and typed actions ## Commands and typed actions
### Services (Portage/systemd ownership) ### Services (Portage/systemd ownership)
@ -160,14 +217,31 @@ with no network and no model.
| 20 | Approval rejected | answer `n` at the prompt | no mutation, nonzero | | 20 | Approval rejected | answer `n` at the prompt | no mutation, nonzero |
| 21 | Plan changed between review and exec | concurrent metadata change | aborts, nonzero | | 21 | Plan changed between review and exec | concurrent metadata change | aborts, nonzero |
| 22 | Offline `sys ask` | `sys ask "<request>"` with no provider | deterministic fallback, nonzero | | 22 | Offline `sys ask` | `sys ask "<request>"` with no provider | deterministic fallback, nonzero |
| 23 | Unqualified install consults the model | `sys install firefox` with a provider | model investigated; resolver confirmed |
| 24 | Explicit backend, no model | `sys install firefox --flatpak` with no provider | deterministic, no model consulted |
| 25 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by the CLI |
| 26 | Explicit lane cannot satisfy | `sys install x --portage` without Portage | explained, no fallback, nonzero |
| 27 | Unqualified with no model | `sys install firefox` and no provider | deterministic offer printed, nothing installed |
| 28 | Ambiguous friendly name | a name matching several candidates | clarification required, nonzero |
| 29 | Fabricated candidate | model proposes a non-existent id | rejected, revised, no install |
| 30 | Changed candidate version | metadata changes after review | approval invalidated, nonzero |
| 31 | Failed install history | a failing backend command | transaction recorded as failed |
Cases 1–14 and 21–22 are covered by host tests Cases 1–14 and 21–31 are covered by host tests
(`crates/phoebus-core/src/selection.rs`, `.../action.rs`, (`crates/phoebus-core/src/selection.rs`, `.../action.rs`,
`crates/phoebus-executor/src/{snap,appimage,ebuild,chooser}.rs`, and `crates/phoebus-ai/src/install.rs`,
`crates/phoebus-installer/tests/sys_cli.rs`). Cases 15–20 and the in-VM subset `crates/phoebus-executor/src/{install,snap,appimage,ebuild,chooser,transaction}.rs`,
of 1–14 are exercised by the VM acceptance script; their current verification and `crates/phoebus-installer/tests/sys_cli.rs`). Cases 15–20 and the in-VM
subset are exercised by the VM acceptance script; their current verification
status is recorded in `docs/STATUS.md`. status is recorded in `docs/STATUS.md`.
Verified in the disposable VM (deterministic minimal install, booted detached):
`sys install app-misc/hello --portage` (plan + effects → snapshot → install →
package-database verification → durable history), `sys remove app-misc/hello`,
the no-model offer and flag-conflict cases, and the read-only investigation
actions; `sys-acceptance.sh` reported `FAIL=0` (19/19). The AI-selected journey
needs a connected model and is the remaining gate (`docs/HANDOFF.md`).
## Security properties ## Security properties
- **No shell.** Every command is an argument vector through - **No shell.** Every command is an argument vector through

View file

@ -0,0 +1,143 @@
# ADR 0013: AI-first package installation workflow
- **Status:** Accepted
- **Date:** 2026-09-24
## Context
ADR 0006 made software selection a shared, hardware- and preference-aware
policy rather than fixed category routing. The remaining gap was the *entry
point*: `sys install <application>` was a thin Portage wrapper and ignored the
connected model, while Flatpak/Nix/Snap/AppImage each had their own command.
A user had to know the right lane in advance.
This ADR defines the installation workflow itself. It supersedes any remaining
fixed category-to-backend routing: the model makes the contextual
recommendation, and the deterministic system validates and executes it.
## Decision
`sys install <application>` is **AI-first**. One shared workflow is used by
ordinary installation, by `sys ask` installation requests, and by explicit
backend flags:
```
request -> identify application -> gather evidence -> AI investigation
-> proposed selection -> deterministic resolution/validation -> review
-> approved execution -> verification -> history
```
The workflow lives in `phoebus-executor::install`; the model loop lives in
`phoebus-ai::install`. The CLI only wires flags and presentation.
### 1. The model investigates with typed, read-only tools
The model has no shell and no filesystem access. It runs a **bounded**
multi-turn investigation and may:
- request evidence with the read-only typed actions `discover_candidates`,
`inspect_candidate`, `check_backend`, `inspect_installation`;
- ask the user a question about intent when system facts cannot answer it;
- then return a structured `InstallProposal { application, backend, candidate,
version, reason, tradeoffs, evidence }`.
Bounds: turn limit, per-turn request limit, evidence-size cap, and
repeated-request detection (the same evidence is never fetched twice; the model
is told to finalise or ask the user). Evidence is untrusted data; it cannot
grant capabilities. Only the four read-only actions are permitted; a proposal
that requests anything mutating fails closed.
### 2. The deterministic resolver is authoritative
The model's proposal is never executed directly. `validate_proposal`:
- re-resolves the application against real backend metadata, including
friendly-name resolution per lane;
- rejects a candidate that is not exactly one the backend reported (fabricated
or stale identifiers), an unavailable candidate, an ambiguous friendly name,
or a duplicate of an existing installation;
- maps the confirmed candidate to the *existing* broker action
(`install_package`, `flatpak_install`, `snap_install`, `nix_prepare`,
`custom_ebuild_install`), so there is no parallel execution path;
- computes concrete effects (Portage `--pretend`, or a synthetic effect for
binary lanes) and a single approval digest.
A rejection is returned to the model as a bounded finding, which may revise its
proposal up to the turn limit.
### 3. Hard rules stay outside model discretion
Portage owns the kernel, drivers, systemd, the host graphics/audio stack and
boot (enforced by the selection policy). Signature verification, architecture
and hardware compatibility, target-root isolation and the privilege boundary
are not proposable. A custom ebuild remains a separately reviewed, untrusted
artifact; the install workflow never builds one as part of "investigation".
### 4. Explicit backend flags are authoritative
`--portage`, `--flatpak`, `--nix`, `--snap`, `--appimage`, `--ebuild`:
- bypass the model entirely and use deterministic resolution within the
requested lane;
- are mutually exclusive (CLI arg group);
- never fall back to another lane: if the lane cannot satisfy the request, the
reason and the alternatives are shown and nothing is installed;
- still require validation, a protective snapshot where applicable,
authentication and review.
Saved preferences inform ordinary AI recommendations; an explicit flag takes
precedence over a saved preference.
### 5. No-model path
For an unqualified install with no reachable provider, the workflow prints the
deterministic candidate selection and the explicit-backend commands, then
**refuses to install**. Provider failure is never treated as permission to
install through a lane. Explicit-backend installation, service management and
recovery remain fully deterministic and model-free.
### 6. One transaction engine, verification, truthful history
All three selection sources execute through the same broker action and the same
transaction engine. The workflow records the transaction **before** the
mutation (so an interrupted run leaves a visible in-progress record), then:
- revalidates the reviewed plan immediately before execution (candidate,
version, action and effects digest); a material change aborts;
- verifies the installed identity and version after execution (`/var/db/pkg`,
`flatpak list`, `snap list`, the managed AppImage record);
- records the final outcome and the protective snapshot.
Success is never claimed merely because a subprocess exited zero: verification
failure is a failed transaction.
## Consequences
- The AI needs bounded, structured tools; the read-only actions are real `sys`
surfaces (`sys --action '{"action":"discover_candidates",...}'`) as well as
model tools.
- A connected model is required for an unqualified `sys install`; this is the
AI-first contract. It is never required to install explicitly, to manage
services, or to recover.
- The resolver and the model must agree on identifiers. The wire names for
backends (`portage-source`, `custom-ebuild`, ...) are the same as
`Backend::as_str`, so evidence and proposals share one vocabulary.
- Multi-turn behaviour depends on the transport. The direct providers carry the
full conversation; the OpenCode adapter concatenates messages, so
investigation is best-effort there.
## Non-goals
- Letting the model execute anything (it cannot).
- Automatically building generated ebuilds during investigation.
- Silent lane switching or duplicate installs.
- Replacing deterministic administration with a model.
## Verification
Unit/integration coverage: the AI loop (steps, bounds, repetition, revision,
provider failure), the resolver (fabrication, ambiguity, duplicate, changed
evidence), the action mapping, the CLI (flag conflicts, no-fallback, no-model
offer), and the transaction begin/finish. VM journeys through `sys install`
(AI-selected and explicit-backend) remain the acceptance gate; see
`docs/SYS.md` and `docs/STATUS.md`.

View file

@ -18,5 +18,6 @@ and link it here.
| [0010](0010-graphical-installer-frontend.md) | Graphical installer frontend and typed bridge | Accepted | | [0010](0010-graphical-installer-frontend.md) | Graphical installer frontend and typed bridge | Accepted |
| [0011](0011-opencode-connection-boundary.md) | OpenCode connection boundary | Accepted | | [0011](0011-opencode-connection-boundary.md) | OpenCode connection boundary | Accepted |
| [0012](0012-nvidia-driver-policy.md) | NVIDIA accelerated-driver policy and payload | Accepted | | [0012](0012-nvidia-driver-policy.md) | NVIDIA accelerated-driver policy and payload | Accepted |
| [0013](0013-ai-first-installation.md) | AI-first package installation workflow | Accepted |
Format: Context / Decision / Consequences / Status. Format: Context / Decision / Consequences / Status.

View file

@ -0,0 +1,712 @@
//! AI-driven installation investigation.
//!
//! The model does not get a shell. It runs a **bounded, multi-turn
//! investigation**: it may ask for typed, read-only evidence (via
//! [`InstallSession::investigate`]), ask the user a question about intent
//! (via [`InstallSession::ask`]), and only then return a structured
//! [`InstallProposal`]. The proposal is validated structurally here and
//! *independently* by the deterministic resolver in `phoebus-executor`, which
//! must confirm the candidate against real backend metadata.
//!
//! Bounds: a turn limit, a per-turn request limit, a response-size limit and
//! repeated-request detection. A repeated evidence request is not executed
//! again; the model is told to finalise or ask the user instead of looping.
use phoebus_core::action::{valid_application_name, valid_candidate_id, SystemAction};
use phoebus_core::selection::Backend;
use serde::{Deserialize, Serialize};
use crate::provider::{
extract_content, ChatMessage, ChatRequest, ModelTransport, ProviderKind, ResponseFormat,
SystemFacts,
};
use crate::AiError;
/// The model's structured installation recommendation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallProposal {
/// The user-facing application (identity, not a backend id).
pub application: String,
pub backend: Backend,
/// The backend-native identifier, copied from evidence.
pub candidate: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Why this candidate suits this machine and request.
pub reason: String,
#[serde(default)]
pub tradeoffs: Vec<String>,
/// Evidence the recommendation rests on (candidate ids, measured facts).
#[serde(default)]
pub evidence: Vec<String>,
}
const MAX_TEXT: usize = 4096;
const MAX_ITEM: usize = 1024;
const MAX_ITEMS: usize = 16;
impl InstallProposal {
/// Structural validation only. The deterministic resolver still confirms
/// the candidate against real metadata; this just rejects malformed or
/// absurd proposals before they reach it.
pub fn validate_structural(&self) -> Result<(), String> {
if !valid_application_name(&self.application) {
return Err(format!("invalid application name: {}", self.application));
}
if !valid_candidate_id(self.backend, &self.candidate) {
return Err(format!(
"invalid {} candidate id: {}",
self.backend.as_str(),
self.candidate
));
}
if self.reason.trim().is_empty() || self.reason.len() > MAX_TEXT {
return Err("a bounded, non-empty reason is required".into());
}
for list in [&self.tradeoffs, &self.evidence] {
if list.len() > MAX_ITEMS {
return Err(format!("at most {MAX_ITEMS} items are allowed"));
}
if list.iter().any(|s| s.len() > MAX_ITEM) {
return Err("an item is too long".into());
}
}
if let Some(version) = &self.version {
if version.len() > 256 || version.chars().any(|c| c.is_control()) {
return Err("invalid version string".into());
}
}
Ok(())
}
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"application: {}\n backend: {}\n candidate: {}\n",
self.application,
self.backend.as_str(),
self.candidate
));
if let Some(version) = &self.version {
out.push_str(&format!(" version: {version}\n"));
}
out.push_str(&format!(" why: {}\n", self.reason));
for t in &self.tradeoffs {
out.push_str(&format!(" tradeoff: {t}\n"));
}
for e in &self.evidence {
out.push_str(&format!(" evidence: {e}\n"));
}
out
}
}
/// A step in the investigation conversation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum InstallStep {
Ask {
question: String,
},
Investigate {
requests: Vec<SystemAction>,
},
Propose {
summary: String,
proposal: InstallProposal,
},
}
/// The closed set of read-only actions the model may request as evidence.
pub fn is_investigation_action(action: &SystemAction) -> bool {
matches!(
action,
SystemAction::DiscoverCandidates { .. }
| SystemAction::InspectCandidate { .. }
| SystemAction::CheckBackend { .. }
| SystemAction::InspectInstallation { .. }
)
}
/// One piece of evidence returned for a request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Evidence {
pub request: String,
pub output: String,
}
/// The system-side half of the loop: produce evidence and, optionally, ask the
/// user a question about intent. Implemented by `phoebus-executor`/`sys`.
pub trait InstallSession {
/// Execute read-only investigation actions and return their evidence.
fn investigate(&self, requests: &[SystemAction]) -> Vec<Evidence>;
/// Ask the user a question about intent or preference. `None` means no
/// answer is available (non-interactive); the model is then told to proceed
/// with a conservative, reversible assumption.
fn ask(&self, question: &str) -> Option<String>;
}
/// Hard bounds on the investigation loop.
#[derive(Debug, Clone)]
pub struct Limits {
pub max_turns: usize,
pub max_requests_per_turn: usize,
/// Maximum bytes of evidence fed back in one turn.
pub max_evidence_bytes: usize,
/// How many times the exact same evidence request set may repeat before the
/// loop refuses to execute it again.
pub max_identical_requests: usize,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_turns: 8,
max_requests_per_turn: 6,
max_evidence_bytes: 24 * 1024,
max_identical_requests: 1,
}
}
}
pub const INSTALL_PROMPT: &str = "\
You are the Phoebus OS installation advisor. The user asked to install an application. \
You must recommend the single best installation option for THIS machine and the user's \
request, using only real candidate identifiers returned to you. You have no shell, no \
root, no filesystem access and no credentials.
Each reply is ONE JSON object with version 2 and a `kind`:
1. Investigate (read-only evidence): \
{\"version\":2,\"kind\":\"investigate\",\"requests\":[<action>,...]}. Allowed actions: \
discover_candidates (query, optional kind/gui/requires_sandbox), inspect_candidate \
(backend, id), check_backend (backend), inspect_installation (application).
2. Ask the user about intent (only when system facts cannot answer): \
{\"version\":2,\"kind\":\"ask\",\"question\":\"...\"}. Use this sparingly, e.g. whether \
the application must access local development tools or a specific file.
3. Propose: {\"version\":2,\"kind\":\"propose\",\"proposal\":{\"application\":\"...\",\
\"backend\":\"...\",\"candidate\":\"...\",\"version\":\"...\",\"reason\":\"...\",\
\"tradeoffs\":[\"...\"],\"evidence\":[\"...\"]}}.
Backends: portage-source, portage-binary, portage-vendor, nix, flatpak, snap, appimage, \
custom-ebuild.
Rules: compare suitable options across lanes; do NOT choose a lane merely because the \
application is a desktop app (Flatpak/Snap) or a developer tool (Nix) — base the choice on \
the machine facts, the user's requirement, permissions, confinement, integration, size, \
measured compile time and update behaviour. Never invent a candidate id, version, size, \
checksum, availability or compatibility: use only what discover_candidates returned. \
Portage owns the kernel, drivers, systemd, the host graphics/audio stack and boot tooling. \
Prefer an existing installation and the user's saved preference; never migrate or duplicate \
silently. If the user asked for a specific backend, honour it. When you have enough \
evidence, propose.";
/// Build the first request of the investigation.
pub fn build_open_request(
provider: ProviderKind,
model: &str,
facts: &SystemFacts,
request: &str,
) -> ChatRequest {
let model = if model.trim().is_empty() {
provider.default_model().to_string()
} else {
model.trim().to_string()
};
let user = format!(
"System facts (JSON):\n{}\n\nUser installation request: {request}\n\n\
Investigate or propose.",
facts.render()
);
ChatRequest {
model,
messages: vec![
ChatMessage {
role: "system".into(),
content: INSTALL_PROMPT.into(),
},
ChatMessage {
role: "user".into(),
content: user,
},
],
temperature: 0.0,
response_format: Some(ResponseFormat {
kind: "json_object".into(),
}),
}
}
/// Parse one model message strictly. Unknown fields, an unsupported version, an
/// unknown kind, or a mutating/invalid investigation action fail closed.
pub fn parse_step(text: &str) -> Result<InstallStep, 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 != 2 {
return Err(AiError::UnsupportedVersion(version as u32));
}
let kind = obj
.get("kind")
.and_then(|k| k.as_str())
.ok_or_else(|| AiError::Rejected("missing `kind`".into()))?;
let allowed: &[&str] = match kind {
"ask" => &["version", "kind", "question"],
"investigate" => &["version", "kind", "requests"],
"propose" => &["version", "kind", "proposal"],
other => return Err(AiError::Rejected(format!("unknown kind `{other}`"))),
};
for key in obj.keys() {
if !allowed.contains(&key.as_str()) {
return Err(AiError::Rejected(format!("unexpected field `{key}`")));
}
}
let get = |key: &str| {
obj.get(key)
.cloned()
.ok_or_else(|| AiError::Rejected(format!("missing `{key}`")))
};
match kind {
"ask" => {
let question: String = serde_json::from_value(get("question")?)?;
if question.trim().is_empty() || question.len() > 1024 {
return Err(AiError::Rejected("invalid question".into()));
}
Ok(InstallStep::Ask { question })
}
"investigate" => {
let requests: Vec<SystemAction> = serde_json::from_value(get("requests")?)?;
for request in &requests {
if !is_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}")))?;
}
Ok(InstallStep::Investigate { requests })
}
"propose" => {
let proposal: InstallProposal = serde_json::from_value(get("proposal")?)?;
proposal.validate_structural().map_err(AiError::Rejected)?;
Ok(InstallStep::Propose {
summary: String::new(),
proposal,
})
}
_ => unreachable!(),
}
}
fn messages_body(request: &ChatRequest) -> Result<String, AiError> {
Ok(serde_json::to_string(request)?)
}
/// Run the bounded investigation and return a structurally valid proposal.
///
/// `validate` is the deterministic resolver's check (provided by the caller).
/// A rejected proposal is fed back to the model for a bounded revision rather
/// than being accepted.
#[allow(clippy::too_many_arguments)]
pub fn investigate_install(
provider: ProviderKind,
endpoint: &str,
model: &str,
facts: &SystemFacts,
request: &str,
transport: &dyn ModelTransport,
session: &dyn InstallSession,
validate: &dyn Fn(&InstallProposal) -> Result<(), String>,
limits: &Limits,
) -> Result<InstallProposal, 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_open_request(provider, model, facts, request);
let mut repeated: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let mut turns = 0usize;
while turns < limits.max_turns {
turns += 1;
let body = messages_body(&chat)?;
let response = transport.send(provider, endpoint, &body)?;
let content = extract_content(&response)?;
let step = parse_step(&content)?;
match step {
InstallStep::Ask { question } => {
chat.messages.push(ChatMessage {
role: "assistant".into(),
content: content.clone(),
});
let answer = session.ask(&question);
let user = match answer {
Some(answer) => format!("The user answered: {answer}"),
None => "No answer is available (non-interactive). Proceed with a \
conservative, reversible choice and state your assumption."
.to_string(),
};
chat.messages.push(ChatMessage {
role: "user".into(),
content: user,
});
}
InstallStep::Investigate { requests } => {
if requests.is_empty() {
return Err(AiError::Rejected("empty investigation request".into()));
}
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
)));
}
for request in &requests {
if !is_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}")))?;
}
// Canonical key: sorted action JSON, so order does not matter.
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. Propose now, or ask the user a question \
if their intent is genuinely unknown."
.to_string(),
});
continue;
}
let evidence = session.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}"),
});
}
InstallStep::Propose { proposal, .. } => {
proposal.validate_structural().map_err(AiError::Rejected)?;
match validate(&proposal) {
Ok(()) => return Ok(proposal),
Err(findings) => {
chat.messages.push(ChatMessage {
role: "assistant".into(),
content: content.clone(),
});
chat.messages.push(ChatMessage {
role: "user".into(),
content: format!(
"Your proposal was rejected by the deterministic resolver: \
{findings}. Investigate further or propose a different, \
real candidate."
),
});
}
}
}
}
}
Err(AiError::Rejected(format!(
"the investigation did not reach a valid proposal within {} turns",
limits.max_turns
)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::provider::chat_response;
fn facts() -> SystemFacts {
SystemFacts {
arch: "x86_64".into(),
cpu_cores: 8,
memory_mib: 16384,
..Default::default()
}
}
struct Sessions {
evidence: std::cell::RefCell<Vec<Vec<SystemAction>>>,
answer: Option<String>,
}
impl InstallSession for Sessions {
fn investigate(&self, requests: &[SystemAction]) -> Vec<Evidence> {
self.evidence.borrow_mut().push(requests.to_vec());
requests
.iter()
.map(|r| Evidence {
request: r.describe(),
output: "[{\"backend\":\"flatpak\",\"id\":\"org.mozilla.firefox\"}]".into(),
})
.collect()
}
fn ask(&self, _q: &str) -> Option<String> {
self.answer.clone()
}
}
fn ok_proposal() -> &'static str {
r#"{"version":2,"kind":"propose","proposal":{"application":"firefox","backend":"flatpak","candidate":"org.mozilla.firefox","reason":"sandboxed, native Wayland","evidence":["org.mozilla.firefox"]}}"#
}
#[test]
fn parse_accepts_the_three_step_kinds() {
let ask = parse_step(r#"{"version":2,"kind":"ask","question":"Do you need dev tools?"}"#)
.unwrap();
assert!(matches!(ask, InstallStep::Ask { .. }));
let inv = parse_step(
r#"{"version":2,"kind":"investigate","requests":[{"action":"discover_candidates","query":"firefox"}]}"#,
)
.unwrap();
assert!(matches!(inv, InstallStep::Investigate { .. }));
let prop = parse_step(ok_proposal()).unwrap();
assert!(matches!(prop, InstallStep::Propose { .. }));
}
#[test]
fn parse_rejects_mutation_unknown_fields_and_bad_version() {
// A mutating action is not a permitted investigation request.
let err = parse_step(
r#"{"version":2,"kind":"investigate","requests":[{"action":"install_package","atom":"vim"}]}"#,
)
.unwrap_err();
assert!(err.to_string().contains("read-only") || err.to_string().contains("permitted"));
// Unknown top-level field.
assert!(parse_step(r#"{"version":2,"kind":"ask","question":"q","shell":"sh"}"#).is_err());
// Unsupported version.
assert!(matches!(
parse_step(r#"{"version":1,"kind":"ask","question":"q"}"#),
Err(AiError::UnsupportedVersion(1))
));
// Bad candidate for the backend.
let bad = r#"{"version":2,"kind":"propose","proposal":{"application":"firefox","backend":"flatpak","candidate":"bad id","reason":"x"}}"#;
assert!(parse_step(bad).unwrap_err().to_string().contains("invalid"));
}
#[test]
fn investigation_then_proposal_succeeds() {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(
r#"{"version":2,"kind":"investigate","requests":[{"action":"discover_candidates","query":"firefox"}]}"#,
),
chat_response(ok_proposal()),
]);
let session = Sessions {
evidence: std::cell::RefCell::new(Vec::new()),
answer: None,
};
let proposal = investigate_install(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install firefox",
&transport,
&session,
&|_| Ok(()),
&Limits::default(),
)
.unwrap();
assert_eq!(proposal.candidate, "org.mozilla.firefox");
assert_eq!(session.evidence.borrow().len(), 1);
let requests = transport.requests();
assert_eq!(requests.len(), 2);
// The second request must carry the evidence back to the model.
assert!(requests[1].contains("org.mozilla.firefox"));
}
#[test]
fn a_rejected_proposal_is_revised_with_findings() {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(ok_proposal()),
chat_response(ok_proposal()),
]);
let session = Sessions {
evidence: std::cell::RefCell::new(Vec::new()),
answer: None,
};
let attempts = std::cell::Cell::new(0);
let validate = |_: &InstallProposal| -> Result<(), String> {
attempts.set(attempts.get() + 1);
if attempts.get() == 1 {
Err("no such Flatpak id in the configured remotes".into())
} else {
Ok(())
}
};
let proposal = investigate_install(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install firefox",
&transport,
&session,
&validate,
&Limits::default(),
)
.unwrap();
assert_eq!(proposal.application, "firefox");
assert_eq!(attempts.get(), 2);
let requests = transport.requests();
assert!(requests[1].contains("rejected"));
}
#[test]
fn truncated_by_the_turn_limit() {
// The model keeps investigating forever; the loop stops.
let transport = crate::provider::ScriptedTransport::new(
(0..10)
.map(|_| {
chat_response(
r#"{"version":2,"kind":"investigate","requests":[{"action":"check_backend","backend":"flatpak"}]}"#,
)
})
.collect(),
);
let session = Sessions {
evidence: std::cell::RefCell::new(Vec::new()),
answer: None,
};
let limits = Limits {
max_turns: 4,
..Default::default()
};
let err = investigate_install(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install x",
&transport,
&session,
&|_| Ok(()),
&limits,
)
.unwrap_err();
assert!(err.to_string().contains("did not reach a valid proposal"));
// The identical evidence is fetched exactly once.
assert_eq!(session.evidence.borrow().len(), 1);
}
#[test]
fn too_many_requests_in_a_turn_are_refused() {
let transport = crate::provider::ScriptedTransport::new(vec![chat_response(
r#"{"version":2,"kind":"investigate","requests":[{"action":"check_backend","backend":"flatpak"},{"action":"check_backend","backend":"nix"},{"action":"check_backend","backend":"snap"},{"action":"check_backend","backend":"appimage"},{"action":"check_backend","backend":"portage-source"},{"action":"check_backend","backend":"portage-binary"},{"action":"check_backend","backend":"custom-ebuild"}]}"#,
)]);
let session = Sessions {
evidence: std::cell::RefCell::new(Vec::new()),
answer: None,
};
let err = investigate_install(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install x",
&transport,
&session,
&|_| Ok(()),
&Limits::default(),
)
.unwrap_err();
assert!(err.to_string().contains("too many"));
assert!(session.evidence.borrow().is_empty());
}
#[test]
fn ask_feeds_the_answer_back_and_none_is_explicit() {
let transport = crate::provider::ScriptedTransport::new(vec![
chat_response(r#"{"version":2,"kind":"ask","question":"Do you need dev tools?"}"#),
chat_response(ok_proposal()),
]);
let session = Sessions {
evidence: std::cell::RefCell::new(Vec::new()),
answer: Some("yes".into()),
};
investigate_install(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install nodejs",
&transport,
&session,
&|_| Ok(()),
&Limits::default(),
)
.unwrap();
assert!(transport.requests()[1].contains("The user answered: yes"));
}
#[test]
fn an_unavailable_provider_is_explicit() {
let transport = crate::provider::TestTransport::new("{}");
let session = Sessions {
evidence: std::cell::RefCell::new(Vec::new()),
answer: None,
};
let err = investigate_install(
ProviderKind::None,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"install x",
&transport,
&session,
&|_| Ok(()),
&Limits::default(),
)
.unwrap_err();
assert!(matches!(err, AiError::ProviderUnavailable(_)));
}
}

View file

@ -7,6 +7,7 @@
//! step performed by the deterministic backend. //! step performed by the deterministic backend.
pub mod assistant; pub mod assistant;
pub mod install;
pub mod privacy; pub mod privacy;
pub mod provider; pub mod provider;

View file

@ -99,6 +99,21 @@ pub struct SystemFacts {
pub recommended_kernel_profile: String, pub recommended_kernel_profile: String,
/// Measured compile times (seconds) for the slowest packages, capped. /// Measured compile times (seconds) for the slowest packages, capped.
pub measured_compile_times: BTreeMap<String, u64>, pub measured_compile_times: BTreeMap<String, u64>,
/// Free space on the intended root, in MiB (`0` means unknown).
#[serde(default)]
pub storage_free_mib: u64,
/// Whether a Wayland session/stack is in use on the intended system.
#[serde(default)]
pub wayland: bool,
/// Lanes whose tooling is present and usable (Portage, Nix, Flatpak, ...).
#[serde(default)]
pub available_backends: Vec<String>,
/// Saved per-application backend preferences.
#[serde(default)]
pub saved_preferences: BTreeMap<String, String>,
/// Whether Btrfs snapshots and rollback are available for recovery.
#[serde(default)]
pub recovery_snapshots: bool,
} }
/// Storage facts supplied by the caller (disk probing lives in the executor). /// Storage facts supplied by the caller (disk probing lives in the executor).
@ -149,6 +164,7 @@ impl SystemFacts {
encryption: config.encryption.mode.to_string(), encryption: config.encryption.mode.to_string(),
recommended_kernel_profile: hardware.recommended_kernel_profile().to_string(), recommended_kernel_profile: hardware.recommended_kernel_profile().to_string(),
measured_compile_times: measured.into_iter().collect(), measured_compile_times: measured.into_iter().collect(),
..Default::default()
} }
} }
@ -179,6 +195,16 @@ impl SystemFacts {
return Err(AiError::PrivateData(atom.clone())); return Err(AiError::PrivateData(atom.clone()));
} }
} }
for backend in &self.available_backends {
if is_forbidden_path(backend) {
return Err(AiError::PrivateData(backend.clone()));
}
}
for (app, backend) in &self.saved_preferences {
if is_forbidden_path(app) || is_forbidden_path(backend) {
return Err(AiError::PrivateData(format!("{app}={backend}")));
}
}
Ok(()) Ok(())
} }
} }

View file

@ -115,6 +115,39 @@ pub enum SystemAction {
backend: Option<Backend>, backend: Option<Backend>,
}, },
// ------------------------------------------------------------------
// Bounded, read-only investigation used by the AI installation workflow.
// These return evidence only; they never mutate the system.
// ------------------------------------------------------------------
/// Discover the real candidates for an application across the available
/// lanes (Portage, Nix, Flatpak, Snap, AppImage, the Phoebus overlay).
DiscoverCandidates {
query: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
kind: Option<PackageKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
#[serde(default)]
gui: bool,
#[serde(default)]
requires_sandbox: bool,
},
/// Inspect one resolved candidate's metadata (version, source, sizes,
/// dependencies, permissions, confinement, update behaviour).
InspectCandidate {
backend: Backend,
id: String,
},
/// Report whether a lane is installed and ready, including daemon state and
/// confinement where relevant.
CheckBackend {
backend: Backend,
},
/// Report existing installations of an application and any duplication.
InspectInstallation {
application: String,
},
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Snap lane. // Snap lane.
// ------------------------------------------------------------------ // ------------------------------------------------------------------
@ -266,6 +299,18 @@ impl SystemAction {
Some(backend) => format!("prefer {} for {name}", backend.as_str()), Some(backend) => format!("prefer {} for {name}", backend.as_str()),
None => format!("clear the backend preference for {name}"), None => format!("clear the backend preference for {name}"),
}, },
SystemAction::DiscoverCandidates { query, .. } => {
format!("discover installation candidates for `{query}`")
}
SystemAction::InspectCandidate { backend, id } => {
format!("inspect the {} candidate {id}", backend.as_str())
}
SystemAction::CheckBackend { backend } => {
format!("check whether the {} lane is ready", backend.as_str())
}
SystemAction::InspectInstallation { application } => {
format!("inspect existing installations of {application}")
}
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 {
@ -341,6 +386,10 @@ impl SystemAction {
| SystemAction::SnapConnections { .. } | SystemAction::SnapConnections { .. }
| SystemAction::AppImageInfo { .. } | SystemAction::AppImageInfo { .. }
| SystemAction::AppImageList | SystemAction::AppImageList
| SystemAction::DiscoverCandidates { .. }
| SystemAction::InspectCandidate { .. }
| SystemAction::CheckBackend { .. }
| SystemAction::InspectInstallation { .. }
| SystemAction::CustomEbuildList => Risk::Low, | SystemAction::CustomEbuildList => Risk::Low,
SystemAction::PrepareUpdates => Risk::Medium, SystemAction::PrepareUpdates => Risk::Medium,
SystemAction::EnableService { .. } SystemAction::EnableService { .. }
@ -389,6 +438,10 @@ impl SystemAction {
| SystemAction::SnapConnections { .. } | SystemAction::SnapConnections { .. }
| SystemAction::AppImageInfo { .. } | SystemAction::AppImageInfo { .. }
| SystemAction::AppImageList | SystemAction::AppImageList
| SystemAction::DiscoverCandidates { .. }
| SystemAction::InspectCandidate { .. }
| SystemAction::CheckBackend { .. }
| SystemAction::InspectInstallation { .. }
| SystemAction::CustomEbuildList | SystemAction::CustomEbuildList
) )
} }
@ -484,6 +537,28 @@ impl SystemAction {
Err(format!("invalid package name: {name}")) Err(format!("invalid package name: {name}"))
} }
} }
SystemAction::DiscoverCandidates { query, .. } => {
if valid_search_query(query) {
Ok(())
} else {
Err(format!("invalid application query: {query}"))
}
}
SystemAction::InspectCandidate { backend, id } => {
if valid_candidate_id(*backend, id) {
Ok(())
} else {
Err(format!("invalid {} candidate id: {id}", backend.as_str()))
}
}
SystemAction::CheckBackend { .. } => Ok(()),
SystemAction::InspectInstallation { application } => {
if valid_application_name(application) {
Ok(())
} else {
Err(format!("invalid application name: {application}"))
}
}
SystemAction::SnapFind { query } => { SystemAction::SnapFind { query } => {
if valid_search_query(query) { if valid_search_query(query) {
Ok(()) Ok(())
@ -729,6 +804,33 @@ 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())
} }
/// A user-facing application name (`firefox`, `org.mozilla.firefox`,
/// `app-editors/vim`). Bounded, no leading dash, no whitespace or controls.
pub fn valid_application_name(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 128
&& !value.starts_with('-')
&& value
.chars()
.all(|c| c.is_ascii_alphanumeric() || "._+@/-".contains(c))
}
/// Validate a backend-native candidate identifier. Each lane has its own
/// identity grammar, so a Portage atom is checked as an atom and a Flatpak
/// application id as a reverse-DNS id; a mismatch fails closed.
pub fn valid_candidate_id(backend: Backend, id: &str) -> bool {
match backend {
Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
valid_package_spec(id)
}
Backend::Nix => valid_nix_attribute(id),
Backend::Flatpak => valid_flatpak_app_id(id),
Backend::Snap => valid_snap_name(id),
Backend::AppImage => valid_appimage_name(id),
Backend::CustomEbuild => valid_ebuild_atom(id),
}
}
/// A real SHA-256: 64 hex characters and not the all-zero placeholder. /// A real SHA-256: 64 hex characters and not the all-zero placeholder.
pub fn valid_sha256(value: &str) -> bool { pub fn valid_sha256(value: &str) -> bool {
value.len() == 64 value.len() == 64
@ -1108,7 +1210,21 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
} }
pub fn parse_action(json: &str) -> Result<SystemAction, ActionError> { pub fn parse_action(json: &str) -> Result<SystemAction, ActionError> {
let action: SystemAction = serde_json::from_str(json)?; let value: serde_json::Value = serde_json::from_str(json)?;
let action: SystemAction = serde_json::from_value(value.clone())?;
// `deny_unknown_fields` does not reject extra keys on internally tagged
// *unit* variants (e.g. `{"action":"history","x":1}`), so compare the
// input keys against the canonical serialisation and fail closed.
if let (Some(input), Some(canonical)) = (
value.as_object(),
serde_json::to_value(&action)?.as_object(),
) {
for key in input.keys() {
if !canonical.contains_key(key) {
return Err(ActionError::Invalid(format!("unknown field `{key}`")));
}
}
}
action.validate().map_err(ActionError::Invalid)?; action.validate().map_err(ActionError::Invalid)?;
Ok(action) Ok(action)
} }
@ -1143,6 +1259,11 @@ mod tests {
assert!(parse_action(r#"{"action":"install_package","atom":"a/b/c"}"#).is_err()); assert!(parse_action(r#"{"action":"install_package","atom":"a/b/c"}"#).is_err());
assert!(parse_action(r#"{"action":"enable_service","name":"bad name"}"#).is_err()); assert!(parse_action(r#"{"action":"enable_service","name":"bad name"}"#).is_err());
assert!(parse_action(r#"{"action":"search_packages","query":""}"#).is_err()); assert!(parse_action(r#"{"action":"search_packages","query":""}"#).is_err());
// Unit variants must reject unknown keys too (serde's
// deny_unknown_fields does not cover internally tagged unit variants).
assert!(parse_action(r#"{"action":"history","x":1}"#).is_err());
assert!(parse_action(r#"{"action":"update_system","shell":"sh"}"#).is_err());
assert!(parse_action(r#"{"action":"snap_list","extra":true}"#).is_err());
} }
#[test] #[test]

View file

@ -282,11 +282,28 @@ pub fn parse_emerge_pretend(text: &str) -> ResolvedPlan {
source, source,
}); });
} }
// `emerge --unmerge --pretend` does not use the `[ebuild ...]` form; it
// lists the packages slated for removal. Parse them so a removal has a
// concrete, reviewable plan instead of being refused as unestablished.
for line in text.lines() {
if let Some(rest) = line.trim().strip_prefix("All selected packages:") {
for atom in rest.split_whitespace() {
plan.effects.push(PackageEffect {
target: atom.to_string(),
previous: None,
kind: EffectKind::Remove,
source: EffectSource::None,
});
}
}
}
// Distinguish a real "0 packages" plan from output we could not parse. A // Distinguish a real "0 packages" plan from output we could not parse. A
// Portage pretend run always prints a recognisable header or totals line. // Portage pretend run always prints a recognisable header or totals line.
plan.established = !plan.effects.is_empty() plan.established = !plan.effects.is_empty()
|| text.contains("These are the packages that would be merged") || text.contains("These are the packages that would be merged")
|| text.contains("Calculating dependencies") || text.contains("Calculating dependencies")
|| text.contains("would be unmerged")
|| text.contains("All selected packages:")
|| text.lines().any(|l| l.trim_start().starts_with("Total:")); || text.lines().any(|l| l.trim_start().starts_with("Total:"));
plan.download_bytes = parse_download_bytes(text); plan.download_bytes = parse_download_bytes(text);
if plan.removals() > 0 { if plan.removals() > 0 {
@ -387,6 +404,19 @@ Total: 5 packages (2 upgrades, 2 new, 1 uninstall), Size of downloads: 10,240 Ki
assert_eq!(plan.digest.len(), 64); assert_eq!(plan.digest.len(), 64);
} }
#[test]
fn parses_unmerge_pretend_output() {
let text = "\n>>> These are the packages that would be unmerged:\n\n \
app-misc/hello\n selected: 2.12.3\n\n\
All selected packages: app-misc/hello-2.12.3\n\n\
>>> 'Selected' packages are slated for removal.\n";
let plan = parse_emerge_pretend(text);
assert!(plan.established, "unmerge output is an established plan");
assert_eq!(plan.removals(), 1);
assert_eq!(plan.effects[0].target, "app-misc/hello-2.12.3");
assert_eq!(plan.effects[0].kind, EffectKind::Remove);
}
#[test] #[test]
fn unparseable_output_is_not_an_empty_plan() { fn unparseable_output_is_not_an_empty_plan() {
// A genuinely empty plan and output we cannot parse must be // A genuinely empty plan and output we cannot parse must be

View file

@ -36,23 +36,30 @@ use crate::hardware::GpuVendor;
/// A software lane. Each maps to a real backend with distinct guarantees. /// A software lane. Each maps to a real backend with distinct guarantees.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Backend { pub enum Backend {
/// Gentoo source ebuild compiled locally. /// Gentoo source ebuild compiled locally.
#[serde(rename = "portage-source")]
PortageSource, PortageSource,
/// A signed binary package from the official Gentoo binhost. /// A signed binary package from the official Gentoo binhost.
#[serde(rename = "portage-binary")]
PortageBinary, PortageBinary,
/// A native vendor-binary ebuild (`-bin`/`-launcher`), e.g. google-chrome. /// A native vendor-binary ebuild (`-bin`/`-launcher`), e.g. google-chrome.
#[serde(rename = "portage-vendor")]
PortageVendor, PortageVendor,
/// Nix (developer tools, alternate versions, reproducible environments). /// Nix (developer tools, alternate versions, reproducible environments).
#[serde(rename = "nix")]
Nix, Nix,
/// Flatpak (sandboxed GUI applications). /// Flatpak (sandboxed GUI applications).
#[serde(rename = "flatpak")]
Flatpak, Flatpak,
/// Snap (sandboxed applications with channel/refresh semantics). /// Snap (sandboxed applications with channel/refresh semantics).
#[serde(rename = "snap")]
Snap, Snap,
/// A managed AppImage (single-file, user-run, no built-in sandbox). /// A managed AppImage (single-file, user-run, no built-in sandbox).
#[serde(rename = "appimage")]
AppImage, AppImage,
/// A Phoebus-managed custom ebuild in the dedicated overlay. /// A Phoebus-managed custom ebuild in the dedicated overlay.
#[serde(rename = "custom-ebuild")]
CustomEbuild, CustomEbuild,
} }
@ -115,17 +122,21 @@ impl Backend {
/// What is being installed. Used for hard rules and as a suitability hint, not /// What is being installed. Used for hard rules and as a suitability hint, not
/// as an automatic routing decision. /// as an automatic routing decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PackageKind { pub enum PackageKind {
/// Kernel, drivers, systemd, host graphics/audio, boot — Portage only. /// Kernel, drivers, systemd, host graphics/audio, boot — Portage only.
#[serde(rename = "base-system")]
BaseSystem, BaseSystem,
/// A graphical desktop application. /// A graphical desktop application.
#[serde(rename = "desktop-app")]
DesktopApp, DesktopApp,
/// A developer tool, runtime or per-project environment. /// A developer tool, runtime or per-project environment.
#[serde(rename = "developer-tool")]
DeveloperTool, DeveloperTool,
/// A command-line administration or utility tool. /// A command-line administration or utility tool.
#[serde(rename = "cli-tool")]
CliTool, CliTool,
#[default] #[default]
#[serde(rename = "unclassified")]
Unclassified, Unclassified,
} }

View file

@ -13,6 +13,9 @@ use crate::error::{CoreError, Result};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)] #[serde(default)]
pub struct TransactionRecord { pub struct TransactionRecord {
/// A stable id, assigned when the transaction begins. A record that never
/// gets a terminal result is an interrupted operation, not a success.
pub id: u64,
pub created_unix: u64, pub created_unix: u64,
/// Where the request came from: `sys` or `assistant`. /// Where the request came from: `sys` or `assistant`.
pub origin: String, pub origin: String,
@ -79,6 +82,7 @@ impl TransactionOutcome {
impl Default for TransactionRecord { impl Default for TransactionRecord {
fn default() -> Self { fn default() -> Self {
Self { Self {
id: 0,
created_unix: 0, created_unix: 0,
origin: String::new(), origin: String::new(),
summary: String::new(), summary: String::new(),
@ -129,10 +133,23 @@ impl TransactionLog {
} }
pub fn save(&self, path: &Path) -> Result<()> { pub fn save(&self, path: &Path) -> Result<()> {
use std::io::Write;
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?; std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?;
} }
std::fs::write(path, toml::to_string_pretty(self)?).map_err(|e| CoreError::io(path, e))?; let text = toml::to_string_pretty(self)?;
let mut file = std::fs::File::create(path).map_err(|e| CoreError::io(path, e))?;
file.write_all(text.as_bytes())
.map_err(|e| CoreError::io(path, e))?;
// Make the record durable: an operation's outcome (including a
// "finished" update to an "in progress" record) must survive a power
// loss, or the history would show a completed action as interrupted.
file.sync_all().map_err(|e| CoreError::io(path, e))?;
if let Some(parent) = path.parent() {
if let Ok(dir) = std::fs::File::open(parent) {
let _ = dir.sync_all();
}
}
Ok(()) Ok(())
} }
@ -187,6 +204,7 @@ mod tests {
let path = dir.path().join("transactions.toml"); let path = dir.path().join("transactions.toml");
let mut log = TransactionLog::default(); let mut log = TransactionLog::default();
log.append(TransactionRecord { log.append(TransactionRecord {
id: 0,
created_unix: 10, created_unix: 10,
origin: "assistant".into(), origin: "assistant".into(),
summary: "install vim".into(), summary: "install vim".into(),
@ -221,6 +239,7 @@ mod tests {
let path = dir.path().join("transactions.toml"); let path = dir.path().join("transactions.toml");
let mut log = TransactionLog::default(); let mut log = TransactionLog::default();
log.append(TransactionRecord { log.append(TransactionRecord {
id: 0,
created_unix: 20, created_unix: 20,
origin: "assistant".into(), origin: "assistant".into(),
summary: "install two".into(), summary: "install two".into(),

View file

@ -532,6 +532,42 @@ pub fn execute(
} }
} }
} }
SystemAction::DiscoverCandidates {
query,
kind,
backend,
gui,
requires_sandbox,
} => {
let need = Need {
name: query.clone(),
kind: (*kind).unwrap_or_else(|| chooser::infer_kind(query)),
requires_sandbox: *requires_sandbox,
requires_proprietary: false,
gui: *gui,
requires_features: Vec::new(),
explicit_backend: *backend,
max_install_mib: None,
};
let candidates = chooser::resolve_candidates(exec, root, &need);
serde_json::to_string_pretty(&candidates)
.unwrap_or_else(|e| format!("could not serialise candidates: {e}"))
}
SystemAction::InspectCandidate { backend, id } => {
let detail = chooser::candidate_detail(exec, root, *backend, id);
serde_json::to_string_pretty(&detail)
.unwrap_or_else(|e| format!("could not serialise candidate: {e}"))
}
SystemAction::CheckBackend { backend } => {
let status = chooser::backend_status(exec, root, *backend);
serde_json::to_string_pretty(&status)
.unwrap_or_else(|e| format!("could not serialise backend status: {e}"))
}
SystemAction::InspectInstallation { application } => {
let inspection = chooser::installed_copies(exec, root, application);
serde_json::to_string_pretty(&inspection)
.unwrap_or_else(|e| format!("could not serialise installations: {e}"))
}
SystemAction::SnapFind { query } => { SystemAction::SnapFind { query } => {
require_host_root(root, "find snaps")?; require_host_root(root, "find snaps")?;
snap::find(exec, query)? snap::find(exec, query)?

View file

@ -145,8 +145,47 @@ pub fn parse_pretend_version(text: &str) -> Option<String> {
None None
} }
/// Split an `emerge`-reported `category/package-version` token into the plain
/// atom and the version. `emerge` rejects a bare versioned atom
/// (`app-misc/hello-2.12.3` is not a valid atom), so the plain atom is the
/// install identifier and the version is recorded separately. Gentoo versions
/// always start with a digit, so the version begins at the last `-` followed
/// by a digit.
pub fn split_atom_version(versioned: &str) -> (String, Option<String>) {
// Drop a `:slot`/`::repo` suffix if present.
let token = versioned.split(':').next().unwrap_or(versioned);
let (category, rest) = match token.split_once('/') {
Some((c, r)) => (Some(c), r),
None => (None, token),
};
let bytes = rest.as_bytes();
let mut split_at: Option<usize> = None;
for i in 1..bytes.len() {
if bytes[i - 1] == b'-' && bytes[i].is_ascii_digit() {
split_at = Some(i - 1);
}
}
match split_at {
Some(i) => {
let package = &rest[..i];
let version = rest[i + 1..].to_string();
let atom = match category {
Some(c) => format!("{c}/{package}"),
None => package.to_string(),
};
(atom, Some(version))
}
None => (token.to_string(), None),
}
}
/// A rough capability profile for a plain Portage source/binary candidate. /// A rough capability profile for a plain Portage source/binary candidate.
fn portage_candidate(id: &str, binary: bool, facts: &HardwareFacts) -> Candidate { fn portage_candidate(
id: &str,
binary: bool,
version: Option<&str>,
facts: &HardwareFacts,
) -> Candidate {
let mut c = Candidate::new( let mut c = Candidate::new(
if binary { if binary {
Backend::PortageBinary Backend::PortageBinary
@ -162,6 +201,7 @@ fn portage_candidate(id: &str, binary: bool, facts: &HardwareFacts) -> Candidate
); );
c.verified = true; c.verified = true;
c.arch = facts.arch.clone(); c.arch = facts.arch.clone();
c.version = version.map(str::to_string);
c.update_reliability = UpdateReliability::Automatic; c.update_reliability = UpdateReliability::Automatic;
if !binary { if !binary {
c.build_seconds = facts.estimated_build_seconds(id); c.build_seconds = facts.estimated_build_seconds(id);
@ -188,14 +228,16 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec<Candidat
match pretend { match pretend {
Ok(resolved) if resolved.success => { Ok(resolved) if resolved.success => {
let text = resolved.stdout_lossy(); let text = resolved.stdout_lossy();
let id = parse_pretend_version(&text).unwrap_or_else(|| name.clone()); let (atom, version) = parse_pretend_version(&text)
out.push(portage_candidate(&id, false, &facts)); .map(|v| split_atom_version(&v))
.unwrap_or_else(|| (name.clone(), None));
out.push(portage_candidate(&atom, false, version.as_deref(), &facts));
if facts.binhost_available { if facts.binhost_available {
out.push(portage_candidate(&id, true, &facts)); out.push(portage_candidate(&atom, true, version.as_deref(), &facts));
} }
} }
_ => { _ => {
let mut c = portage_candidate(name, false, &facts); let mut c = portage_candidate(name, false, None, &facts);
c.available = false; c.available = false;
c.notes c.notes
.push("emerge could not resolve this name from the Gentoo tree".into()); .push("emerge could not resolve this name from the Gentoo tree".into());
@ -403,6 +445,477 @@ pub fn infer_kind(_name: &str) -> PackageKind {
PackageKind::Unclassified PackageKind::Unclassified
} }
// ---------------------------------------------------------------------------
// Structured, read-only evidence for the AI installation workflow.
// ---------------------------------------------------------------------------
/// A candidate plus the extra, backend-specific evidence that is only fetched
/// on demand (dependencies, confinement, channels).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct CandidateDetail {
#[serde(flatten)]
pub candidate: Candidate,
/// The transitive merge/dependency set, when the backend can report it.
pub dependencies: Vec<String>,
/// Snap confinement (`strict`/`partial`/`none`), when applicable.
#[serde(skip_serializing_if = "Option::is_none")]
pub confinement: Option<String>,
/// Snap channel, when applicable.
#[serde(skip_serializing_if = "Option::is_none")]
pub channel: Option<String>,
}
/// Whether a lane is installed and ready on the intended system.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct BackendStatus {
pub backend: String,
pub available: bool,
/// A bounded, human-readable explanation (never invented).
pub detail: String,
}
/// One existing installation of an application.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct InstalledCopy {
pub backend: String,
pub id: String,
pub version: String,
}
/// What is already installed for an application, and whether it is duplicated
/// across lanes (which must never be created silently).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct InstallationInspection {
pub application: String,
pub copies: Vec<InstalledCopy>,
pub duplicate: bool,
}
/// Inspect one candidate's metadata, using only what the backend actually
/// reports. A candidate that cannot be resolved is returned as unavailable
/// rather than invented.
pub fn candidate_detail(exec: &Exec, root: &Path, backend: Backend, id: &str) -> CandidateDetail {
let need = Need::new(id);
let mut candidate = resolve_candidates(exec, root, &need)
.into_iter()
.find(|c| c.backend == backend && c.id == id);
let mut dependencies = Vec::new();
let mut confinement = None;
let mut channel = None;
match backend {
Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "inspect candidate dependencies", "emerge")
.args(["--pretend", "--quiet", "--color=n", "--"])
.arg(id),
) {
if out.success {
let plan = phoebus_core::effects::parse_emerge_pretend(&out.stdout_lossy());
dependencies = plan.effects.into_iter().map(|e| e.target).collect();
}
}
}
Backend::Snap => {
if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "inspect snap candidate", "snap").args([
"info",
id,
"--color=never",
]),
) {
if out.success {
let text = out.stdout_lossy();
let (version, chan, conf) = crate::snap::parse_info_summary(&text);
if let Some(c) = candidate.as_mut() {
if c.version.is_none() {
c.version = version;
}
}
channel = chan;
confinement = Some(conf.as_str().to_string());
}
}
}
Backend::Flatpak | Backend::Nix | Backend::AppImage | Backend::CustomEbuild => {}
}
let candidate = candidate.unwrap_or_else(|| {
let mut c = Candidate::new(backend, id, "(unresolved)");
c.available = false;
c.notes
.push("this backend could not resolve the candidate from real metadata".into());
c
});
CandidateDetail {
candidate,
dependencies,
confinement,
channel,
}
}
/// The result of resolving a friendly application name within one lane.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct BackendResolution {
pub backend: String,
pub candidates: Vec<Candidate>,
/// Every identifier that matched a friendly name, when it was not itself an
/// exact identifier and more than one candidate matched. A non-empty list
/// means the caller must ask the user which one is intended.
pub ambiguous: Vec<String>,
}
impl BackendResolution {
pub fn unambiguous(&self) -> Option<&Candidate> {
if self.ambiguous.is_empty() && self.candidates.len() == 1 {
self.candidates.first()
} else {
None
}
}
pub fn is_ambiguous(&self) -> bool {
!self.ambiguous.is_empty() || self.candidates.len() > 1
}
}
/// Resolve an application name within one lane, including friendly names where
/// the lane exposes an authoritative search. Only real metadata is used; an
/// unknown name yields no candidate (never a fabricated one).
pub fn resolve_for_backend(
exec: &Exec,
root: &Path,
backend: Backend,
application: &str,
) -> BackendResolution {
let mut candidates: Vec<Candidate> = Vec::new();
let mut ambiguous: Vec<String> = Vec::new();
let exact = |id: &str| id == application;
match backend {
Backend::Flatpak => {
if crate::exec::find_in_path("flatpak").is_some() {
if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "resolve flatpak name", "flatpak").args([
"search",
"--columns=application,version",
"--",
application,
]),
) {
if out.success {
let mut matches: Vec<(String, String)> = Vec::new();
for line in out.stdout_lossy().lines() {
let mut cols = line.split_whitespace();
if let (Some(id), Some(version)) = (cols.next(), cols.next()) {
if id.contains('.') {
matches.push((id.to_string(), version.to_string()));
}
}
}
let exact_matches: Vec<_> = matches
.iter()
.filter(|(id, _)| exact(id))
.cloned()
.collect();
if !exact_matches.is_empty() {
for (id, version) in exact_matches {
let mut c = Candidate::new(Backend::Flatpak, id, "flathub");
c.version = Some(version);
c.verified = true;
c.sandbox = SandboxLevel::Strong;
c.update_reliability = UpdateReliability::Automatic;
candidates.push(c);
}
} else if matches.len() == 1 {
let (id, version) = matches.pop().unwrap();
let mut c = Candidate::new(Backend::Flatpak, id, "flathub");
c.version = Some(version);
c.verified = true;
c.sandbox = SandboxLevel::Strong;
c.update_reliability = UpdateReliability::Automatic;
c.notes
.push(format!("matched the friendly name `{application}`"));
candidates.push(c);
} else if matches.len() > 1 {
ambiguous = matches.into_iter().map(|(id, _)| id).collect();
}
}
}
}
}
Backend::Snap => {
if matches!(crate::snap::status(exec), Ok(s) if s.usable()) {
if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "resolve snap name", "snap").args([
"find",
"--color=never",
"--",
application,
]),
) {
if out.success {
let found = crate::snap::parse_find(&out.stdout_lossy());
let exact_matches: Vec<_> =
found.iter().filter(|c| exact(&c.name)).cloned().collect();
if !exact_matches.is_empty() {
for hit in exact_matches {
candidates.push(snap_candidate(hit.name, hit.version, false));
}
} else if found.len() == 1 {
let hit = &found[0];
let mut c =
snap_candidate(hit.name.clone(), hit.version.clone(), false);
c.notes
.push(format!("matched the friendly name `{application}`"));
candidates.push(c);
} else if found.len() > 1 {
ambiguous = found.into_iter().map(|c| c.name).collect();
}
}
}
}
}
Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => {
// Portage resolves bare names itself; confirm the atom is real.
if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "resolve portage name", "emerge")
.args(["--pretend", "--quiet", "--color=n", "--"])
.arg(application),
) {
if out.success {
let (atom, version) = parse_pretend_version(&out.stdout_lossy())
.map(|v| split_atom_version(&v))
.unwrap_or_else(|| (application.to_string(), None));
candidates.push(portage_candidate(
&atom,
backend == Backend::PortageBinary,
version.as_deref(),
&hardware_facts(exec, root),
));
}
}
}
Backend::Nix => {
if crate::nix::installed(root) && phoebus_core::action::valid_nix_attribute(application)
{
let mut c = Candidate::new(Backend::Nix, application, "nixpkgs (pinned)");
c.verified = true;
c.update_reliability = UpdateReliability::Automatic;
candidates.push(c);
}
}
Backend::AppImage => {
if let Ok(record) = crate::appimage::info(root, application) {
let mut c = Candidate::new(
Backend::AppImage,
record.name.clone(),
record.provenance.clone(),
);
c.version = Some(record.version.clone());
c.verified = true;
c.sandbox = SandboxLevel::None;
c.arch = record.arch.clone();
candidates.push(c);
}
}
Backend::CustomEbuild => {
let staged = crate::ebuild::list(root);
let matches: Vec<_> = staged
.into_iter()
.filter(|s| s.atom == application || s.package_name() == application)
.collect();
if matches.len() == 1 {
let s = &matches[0];
let mut c = Candidate::new(
Backend::CustomEbuild,
s.atom.clone(),
"Phoebus overlay (/var/db/repos/phoebus)",
);
c.version = Some(s.version.clone());
candidates.push(c);
} else if matches.len() > 1 {
ambiguous = matches.into_iter().map(|s| s.atom).collect();
}
}
}
BackendResolution {
backend: backend.as_str().to_string(),
candidates,
ambiguous,
}
}
fn snap_candidate(name: String, version: String, classic: bool) -> Candidate {
let mut c = Candidate::new(Backend::Snap, name, "Snap Store");
c.version = Some(version);
c.verified = true;
c.sandbox = if classic {
SandboxLevel::None
} else {
SandboxLevel::Strong
};
c.update_reliability = UpdateReliability::Automatic;
c
}
/// Report whether a lane is present and ready.
pub fn backend_status(exec: &Exec, root: &Path, backend: Backend) -> BackendStatus {
let facts = hardware_facts(exec, root);
let available = facts.backend_available(backend);
let detail = match backend {
Backend::PortageSource | Backend::PortageVendor => {
if crate::exec::find_in_path("emerge").is_some() {
"Portage (emerge) is present".into()
} else {
"emerge is not in PATH".into()
}
}
Backend::PortageBinary => {
if root.join("etc/portage/binrepos.conf").exists() {
"a signed binary host is configured".into()
} else {
"no binhost is configured; source builds would be used".into()
}
}
Backend::Nix => {
if crate::nix::installed(root) {
"the Nix store is present".into()
} else {
"Nix is not installed in this target".into()
}
}
Backend::Flatpak => {
if crate::exec::find_in_path("flatpak").is_some() {
"the flatpak client is present".into()
} else {
"flatpak is not installed".into()
}
}
Backend::Snap => match crate::snap::status(exec) {
Ok(s) => format!(
"snap client present: {}, daemon active: {}, confinement: {}",
s.client_present,
s.daemon_ready,
s.confinement.as_str()
),
Err(_) => "snapd state could not be determined".into(),
},
Backend::AppImage => "AppImages can be imported or downloaded locally".into(),
Backend::CustomEbuild => {
if crate::ebuild::list(root).is_empty() {
"no custom ebuilds are staged".into()
} else {
"the Phoebus overlay is present with staged ebuilds".into()
}
}
};
BackendStatus {
backend: backend.as_str().to_string(),
available,
detail,
}
}
/// Inspect what is already installed for an application across lanes. Never
/// invents a copy; every entry comes from a real backend inventory.
pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> InstallationInspection {
let mut copies = Vec::new();
// Flatpak.
if crate::exec::find_in_path("flatpak").is_some() {
if let Ok(out) = exec.runner.execute(
&CommandSpec::new("sys", "inspect installed flatpaks", "flatpak").args([
"list",
"--app",
"--columns=application,version",
]),
) {
if out.success {
for line in out.stdout_lossy().lines() {
let mut cols = line.split_whitespace();
if let (Some(id), Some(version)) = (cols.next(), cols.next()) {
if id == application {
copies.push(InstalledCopy {
backend: Backend::Flatpak.as_str().into(),
id: id.to_string(),
version: version.to_string(),
});
}
}
}
}
}
}
// Snap.
if let Ok(entries) = crate::snap::list(exec) {
for entry in entries {
if entry.name == application {
copies.push(InstalledCopy {
backend: Backend::Snap.as_str().into(),
id: entry.name,
version: entry.version,
});
}
}
}
// AppImage (managed record).
if let Ok(record) = crate::appimage::info(root, application) {
copies.push(InstalledCopy {
backend: Backend::AppImage.as_str().into(),
id: record.name,
version: record.version,
});
}
// Portage (VDB).
if let Some(version) = portage_installed_version(root, application) {
copies.push(InstalledCopy {
backend: Backend::PortageSource.as_str().into(),
id: application.to_string(),
version,
});
}
let duplicate = copies.len() > 1;
InstallationInspection {
application: application.to_string(),
copies,
duplicate,
}
}
/// The installed version of a Portage package from the VDB, if present.
fn portage_installed_version(root: &Path, name: &str) -> Option<String> {
let vdb = root.join("var/db/pkg");
let (category, package) = match name.split_once('/') {
Some((c, p)) => (Some(c.to_string()), p.to_string()),
None => (None, name.to_string()),
};
let categories = std::fs::read_dir(&vdb).ok()?;
for category_entry in categories.flatten() {
let category_name = category_entry.file_name().to_string_lossy().to_string();
if let Some(want) = &category {
if &category_name != want {
continue;
}
}
let pkgs = std::fs::read_dir(category_entry.path()).ok()?;
for pkg in pkgs.flatten() {
let dir = pkg.file_name().to_string_lossy().to_string();
if let Some(rest) = dir.strip_prefix(&format!("{package}-")) {
return Some(rest.to_string());
}
}
}
None
}
/// A plain-text inventory of the available lanes, for `sys choose` with no /// A plain-text inventory of the available lanes, for `sys choose` with no
/// request and for diagnostics. /// request and for diagnostics.
pub fn lanes_report(exec: &Exec, root: &Path) -> String { pub fn lanes_report(exec: &Exec, root: &Path) -> String {
@ -462,6 +975,49 @@ mod tests {
assert_eq!(parse_pretend_version("nothing here"), None); assert_eq!(parse_pretend_version("nothing here"), None);
} }
#[test]
fn split_atom_version_recovers_the_plain_install_atom() {
// emerge rejects `cat/pkg-version`, so the install id must stay plain.
assert_eq!(
split_atom_version("app-misc/hello-2.12.3"),
("app-misc/hello".to_string(), Some("2.12.3".to_string()))
);
assert_eq!(
split_atom_version("dev-lang/python-3.12.6:3.12"),
("dev-lang/python".to_string(), Some("3.12.6".to_string()))
);
assert_eq!(
split_atom_version("www-client/firefox-128.0::gentoo"),
("www-client/firefox".to_string(), Some("128.0".to_string()))
);
assert_eq!(
split_atom_version("sys-apps/foo-bar-1.0-r1"),
("sys-apps/foo-bar".to_string(), Some("1.0-r1".to_string()))
);
assert_eq!(split_atom_version("vim"), ("vim".to_string(), None));
}
#[test]
fn portage_candidate_keeps_a_valid_install_atom() {
let runner = RecordingRunner::new();
runner.set_response(
"emerge",
ok("Calculating dependencies... done!\n[ebuild N ] app-misc/hello-2.12.3 USE=\"nls\"\n"),
);
let exec = make_exec(runner);
let root = tempfile::tempdir().unwrap();
let need = Need::new("app-misc/hello");
let candidates = resolve_candidates(&exec, root.path(), &need);
let portage = candidates
.iter()
.find(|c| c.backend == Backend::PortageSource && c.available)
.expect("portage candidate");
assert_eq!(portage.id, "app-misc/hello");
assert_eq!(portage.version.as_deref(), Some("2.12.3"));
// And the id is a valid package spec that emerge accepts.
assert!(phoebus_core::action::valid_package_spec(&portage.id));
}
#[test] #[test]
fn preferences_roundtrip_through_disk() { fn preferences_roundtrip_through_disk() {
let root = tempfile::tempdir().unwrap(); let root = tempfile::tempdir().unwrap();
@ -532,4 +1088,34 @@ mod tests {
assert!(report.contains(backend.as_str()), "missing {backend:?}"); assert!(report.contains(backend.as_str()), "missing {backend:?}");
} }
} }
#[test]
fn target_facts_are_read_from_the_target_not_the_host() {
// A binhost configured in one root must not appear in another: the
// host's own configuration must never leak into a target's facts.
let exec = make_exec(RecordingRunner::new());
let with_binhost = tempfile::tempdir().unwrap();
std::fs::create_dir_all(with_binhost.path().join("etc/portage")).unwrap();
std::fs::write(with_binhost.path().join("etc/portage/binrepos.conf"), "x").unwrap();
let without = tempfile::tempdir().unwrap();
let a = hardware_facts(&exec, with_binhost.path());
let b = hardware_facts(&exec, without.path());
assert!(a.binhost_available);
assert!(!b.binhost_available);
assert!(a.available_backends.contains(&Backend::PortageBinary));
assert!(!b.available_backends.contains(&Backend::PortageBinary));
}
#[test]
fn installed_copies_reports_duplication_and_versions() {
let runner = RecordingRunner::new();
runner.set_response("flatpak", ok("org.mozilla.firefox 128\n"));
let exec = make_exec(runner);
let root = tempfile::tempdir().unwrap();
let inspection = installed_copies(&exec, root.path(), "org.mozilla.firefox");
assert_eq!(inspection.copies.len(), 1);
assert_eq!(inspection.copies[0].version, "128");
assert!(!inspection.duplicate);
}
} }

File diff suppressed because it is too large Load diff

View file

@ -17,6 +17,7 @@ pub mod ebuild;
pub mod encryption; pub mod encryption;
pub mod error; pub mod error;
pub mod exec; pub mod exec;
pub mod install;
pub mod kernel; pub mod kernel;
pub mod live_nvidia; pub mod live_nvidia;
pub mod log; pub mod log;

View file

@ -2,7 +2,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use phoebus_core::transaction::{TransactionLog, TransactionRecord}; use phoebus_core::transaction::{TransactionLog, TransactionOutcome, TransactionRecord};
use crate::error::{ExecError, Result}; use crate::error::{ExecError, Result};
use crate::exec::Exec; use crate::exec::Exec;
@ -25,6 +25,56 @@ pub fn append(exec: &Exec, root: &Path, record: TransactionRecord) -> Result<()>
Ok(()) Ok(())
} }
fn now_id() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
.max(1)
}
/// Record a transaction **before** the mutation starts. Returns its id; a
/// record that never reaches [`finish`] is an interrupted operation, not a
/// success.
pub fn begin(exec: &Exec, root: &Path, mut record: TransactionRecord) -> Result<u64> {
let id = if record.id != 0 { record.id } else { now_id() };
record.id = id;
if record.result.trim().is_empty() {
record.result = "in progress".into();
}
append(exec, root, record)?;
Ok(id)
}
/// Complete a transaction begun with [`begin`], preserving the same record so
/// the history shows one entry per operation.
pub fn finish(
exec: &Exec,
root: &Path,
id: u64,
result: impl Into<String>,
snapshot: Option<String>,
outcomes: Vec<TransactionOutcome>,
) -> Result<()> {
let mut log = read(root)?;
let record = log.records.iter_mut().find(|r| r.id == id).ok_or_else(|| {
ExecError::operation(
"transaction",
"finish",
"no in-progress transaction with that id",
)
})?;
record.result = result.into();
if snapshot.is_some() {
record.snapshot = snapshot;
}
record.outcomes = outcomes;
log.save(&path(root)).map_err(ExecError::Core)?;
exec.logger.info("updated transaction");
Ok(())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -58,4 +108,91 @@ mod tests {
assert_eq!(log.records.len(), 1); assert_eq!(log.records.len(), 1);
assert_eq!(log.records[0].origin, "sys"); assert_eq!(log.records[0].origin, "sys");
} }
#[test]
fn begin_records_in_progress_and_finish_updates_the_same_record() {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(RecordingRunner::new()),
logger,
false,
path.join("root"),
path,
);
let root = Path::new(&exec.root);
let id = begin(
&exec,
root,
TransactionRecord {
origin: "sys".into(),
summary: "install firefox".into(),
result: String::new(),
..Default::default()
},
)
.unwrap();
// Before finish, the record is visibly in progress.
let log = read(root).unwrap();
assert_eq!(log.records.len(), 1);
assert_eq!(log.records[0].result, "in progress");
assert_eq!(log.records[0].id, id);
finish(
&exec,
root,
id,
"ok",
None,
vec![TransactionOutcome::completed("install firefox")],
)
.unwrap();
let log = read(root).unwrap();
// Still one record, now complete.
assert_eq!(log.records.len(), 1);
assert_eq!(log.records[0].result, "ok");
assert_eq!(log.records[0].outcome_counts(), (1, 0, 0));
}
#[test]
fn a_failed_operation_is_recorded_truthfully() {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(RecordingRunner::new()),
logger,
false,
path.join("root"),
path,
);
let root = Path::new(&exec.root);
let id = begin(
&exec,
root,
TransactionRecord {
origin: "sys".into(),
summary: "install firefox".into(),
result: String::new(),
..Default::default()
},
)
.unwrap();
finish(
&exec,
root,
id,
"failed: network unreachable",
None,
vec![TransactionOutcome::failed(
"install firefox",
"network unreachable",
)],
)
.unwrap();
let log = read(root).unwrap();
assert_eq!(log.records.len(), 1);
assert!(log.records[0].result.starts_with("failed"));
assert_eq!(log.records[0].outcome_counts(), (0, 1, 0));
assert!(log.render().contains("Failed"));
}
} }

View file

@ -13,16 +13,25 @@ use clap::Parser;
use phoebus_ai::assistant::{complete_plan, AssistantPlan}; use phoebus_ai::assistant::{complete_plan, AssistantPlan};
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts}; use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
use phoebus_core::action::{parse_action, parse_natural, SystemAction}; use phoebus_core::action::{parse_action, parse_natural, SystemAction};
use phoebus_core::selection::Backend;
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
use phoebus_core::{AiBackend, InstallConfig, Redactor}; use phoebus_core::{AiBackend, InstallConfig, Redactor};
use phoebus_executor::install::{self, AiInstall, ExecutorSession, InstallRequest};
use phoebus_executor::opencode_client::ExecOpenCodeTransport; use phoebus_executor::opencode_client::ExecOpenCodeTransport;
use phoebus_executor::{ use phoebus_executor::{
actions, authorize, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization, actions, authorize, chooser, probe, transaction, AutoConfirm, Confirmation,
Exec, Logger, RealRunner, Result, DestructiveAuthorization, Exec, Logger, RealRunner, Result,
}; };
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command(name = "sys", about = "Phoebus system interface", version)] #[command(
name = "sys",
about = "Phoebus system interface",
version,
group(clap::ArgGroup::new("backend").args([
"portage", "flatpak", "nix", "snap", "appimage", "ebuild"
]).multiple(false))
)]
struct Cli { struct Cli {
/// Natural-language instruction, e.g. `enable sshd`. /// Natural-language instruction, e.g. `enable sshd`.
text: Vec<String>, text: Vec<String>,
@ -43,6 +52,30 @@ struct Cli {
#[arg(long, default_value = "/")] #[arg(long, default_value = "/")]
root: PathBuf, root: PathBuf,
/// Install through Portage only (no model needed).
#[arg(long)]
portage: bool,
/// Install from Flatpak only (no model needed).
#[arg(long)]
flatpak: bool,
/// Install from Nix only (no model needed).
#[arg(long)]
nix: bool,
/// Install from Snap only (no model needed).
#[arg(long)]
snap: bool,
/// Install a managed AppImage only (no model needed).
#[arg(long)]
appimage: bool,
/// Build and install a staged custom ebuild only (no model needed).
#[arg(long)]
ebuild: bool,
/// AI provider for `sys ask`: deepseek, openai, or local. /// AI provider for `sys ask`: deepseek, openai, or local.
#[arg(long, value_name = "PROVIDER")] #[arg(long, value_name = "PROVIDER")]
ai_provider: Option<String>, ai_provider: Option<String>,
@ -180,6 +213,21 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
return run_ask(&cli, &exec, &instruction); return run_ask(&cli, &exec, &instruction);
} }
// `sys install <application>` is AI-first: a connected model investigates
// and recommends, while an explicit backend flag is deterministic and needs
// no model. Both share `phoebus_executor::install`.
let backend = backend_flag(&cli);
if let Some(application) = parse_install_text(&cli.text.join(" ")) {
return run_install(&cli, &exec, &application, backend);
}
if backend.is_some() {
return Err(
"--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \
`sys install <application>`"
.into(),
);
}
let action = if let Some(json) = &cli.action { let action = if let Some(json) = &cli.action {
parse_action(json)? parse_action(json)?
} else if let Some(path) = &cli.action_file { } else if let Some(path) = &cli.action_file {
@ -251,6 +299,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
if action.is_mutating() { if action.is_mutating() {
let described = action.describe(); let described = action.describe();
let record = TransactionRecord { let record = TransactionRecord {
id: 0,
created_unix: now_unix(), created_unix: now_unix(),
origin: "sys".into(), origin: "sys".into(),
summary: described.clone(), summary: described.clone(),
@ -265,14 +314,376 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
Ok(()) Ok(())
} }
/// A caller-provided question/answer function for the AI install loop.
type AskFn = dyn Fn(&str) -> Option<String>;
/// Map the explicit backend flags to a lane. The clap arg group forbids more
/// than one, so at most one is set.
fn backend_flag(cli: &Cli) -> Option<Backend> {
if cli.portage {
Some(Backend::PortageSource)
} else if cli.flatpak {
Some(Backend::Flatpak)
} else if cli.nix {
Some(Backend::Nix)
} else if cli.snap {
Some(Backend::Snap)
} else if cli.appimage {
Some(Backend::AppImage)
} else if cli.ebuild {
Some(Backend::CustomEbuild)
} else {
None
}
}
/// Parse `install <application>` / `add <application>`. Option-like operands
/// are left to the deterministic parser so `install --color=n` is still
/// rejected as before.
fn parse_install_text(text: &str) -> Option<String> {
let trimmed = text.trim();
let lower = trimmed.to_ascii_lowercase();
for prefix in ["install ", "add "] {
if lower.starts_with(prefix) {
let app = trimmed[prefix.len()..].trim();
if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') {
return Some(app.to_string());
}
}
}
None
}
/// Load the installed system's configuration instead of assuming defaults.
/// Distinguishes the real target from the development host (the root is the
/// target; nothing here reads the host's own configuration).
fn load_installed_config(root: &Path) -> InstallConfig {
let path = root.join("etc/phoebus/install.toml");
std::fs::read_to_string(&path)
.ok()
.and_then(|text| InstallConfig::from_toml(&text).ok())
.unwrap_or_default()
}
/// A bounded asker for questions about user intent. Disabled under `--yes` or
/// when stdin is not a terminal: the AI loop is then told to proceed with a
/// conservative assumption.
fn install_asker(cli: &Cli) -> Option<Box<AskFn>> {
use std::io::IsTerminal;
if cli.yes || !std::io::stdin().is_terminal() {
return None;
}
Some(Box::new(|question: &str| {
println!("\nThe assistant needs to know: {question}");
eprint!("> ");
use std::io::Write;
std::io::stdout().flush().ok();
let mut line = String::new();
match std::io::stdin().read_line(&mut line) {
Ok(n) if n > 0 => {
let t = line.trim();
if t.is_empty() {
None
} else {
Some(t.to_string())
}
}
_ => None,
}
}))
}
/// Explain that an unqualified install needs a model, and show the
/// deterministic candidate selection without installing it.
fn print_install_offer(cli: &Cli, exec: &Exec, application: &str) {
let need = InstallRequest::new(application).need();
match chooser::choose(exec, &cli.root, &need) {
Ok(selection) => println!("{}", selection.render()),
Err(e) => eprintln!("sys: the deterministic selector also found no candidate: {e}"),
}
eprintln!();
eprintln!("No connected model is available for an unqualified install, so Phoebus will");
eprintln!("not choose a lane for you. Install explicitly, for example:");
eprintln!(" sys install {application} --flatpak");
eprintln!(" sys install {application} --portage");
eprintln!(" sys install {application} --nix");
eprintln!(" sys install {application} --snap");
eprintln!(" sys install {application} --appimage");
eprintln!(" sys install {application} --ebuild");
}
/// `sys install <application>`: the shared installation workflow.
fn run_install(
cli: &Cli,
exec: &Exec,
application: &str,
backend: Option<Backend>,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let mut request = InstallRequest::new(application);
request.backend = backend;
// An explicit backend is deterministic and works without a model.
if backend.is_some() {
let resolved = install::resolve_explicit(exec, &cli.root, &request)?;
return execute_resolved(cli, exec, resolved);
}
// Unqualified: the configured model investigates and recommends. A
// provider failure never becomes permission to install through a lane.
let conf = load_installed_ai_config(&cli.root);
let ai_backend = resolve_backend(cli, conf.as_ref());
let facts = gather_facts(exec);
let (provider, endpoint, model);
let transport: Box<dyn ModelTransport + '_>;
match ai_backend {
AiBackend::OpenCode => {
let server = cli
.opencode_server
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_server.clone()))
.unwrap_or_default();
let opencode_provider = cli
.opencode_provider
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_provider.clone()))
.unwrap_or_default();
let opencode_model = cli
.opencode_model
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
.or_else(|| conf.as_ref().map(|c| c.opencode_model.clone()))
.unwrap_or_default();
if server.trim().is_empty()
|| opencode_provider.trim().is_empty()
|| opencode_model.trim().is_empty()
{
print_install_offer(cli, exec, application);
return Err(
"OpenCode needs --opencode-server, --opencode-provider and --opencode-model"
.into(),
);
}
let password = match &cli.opencode_password_file {
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
None => None,
};
provider = ProviderKind::Local;
endpoint = server;
model = opencode_model;
transport = Box::new(
ExecOpenCodeTransport::new(
exec,
endpoint.clone(),
opencode_provider,
model.clone(),
)
.with_auth(password),
);
}
AiBackend::Direct => {
provider = resolve_provider(cli, conf.as_ref());
if provider == ProviderKind::None {
print_install_offer(cli, exec, application);
return Err("no AI provider configured for an unqualified install".into());
}
let key = match api_key_file(cli) {
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
None => None,
};
if provider.requires_key() && key.is_none() {
print_install_offer(cli, exec, application);
return Err(format!(
"provider `{}` requires --ai-api-key-file (mode 0600)",
provider.as_str()
)
.into());
}
endpoint = resolve_endpoint(cli, provider, conf.as_ref());
model = resolve_model(cli, conf.as_ref());
let direct = phoebus_executor::ai::CurlTransport::new(exec, key);
transport = if cli.no_sandbox {
Box::new(direct)
} else {
Box::new(direct.sandboxed())
};
}
}
eprintln!(
"Investigating `{application}` with {} (bounded, read-only evidence only)...",
provider.as_str()
);
let ai = AiInstall {
provider,
endpoint,
model,
transport: transport.as_ref(),
limits: phoebus_ai::install::Limits::default(),
};
let asker = install_asker(cli);
let session = ExecutorSession {
exec,
root: &cli.root,
ask: asker.as_deref(),
};
let resolved = match install::resolve_with_ai(exec, &cli.root, &request, &session, &ai, &facts)
{
Ok(resolved) => resolved,
Err(e) => {
// The model failed: offer the deterministic path and stop; do not
// install through any backend.
print_install_offer(cli, exec, application);
return Err(format!("the AI investigation did not produce a plan: {e}").into());
}
};
execute_resolved(cli, exec, resolved)
}
/// Present, approve, execute, verify and record a resolved installation. This
/// is the single execution path for AI-, explicit- and deterministic-selected
/// installs.
fn execute_resolved(
cli: &Cli,
exec: &Exec,
resolved: install::ResolvedInstall,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
println!("{}", resolved.render());
if effective_uid() != 0 {
return Err(format!(
"installing `{}` requires root; run `sudo sys install {}`",
resolved.request.application, resolved.request.application
)
.into());
}
let confirmation = SysConfirm {
action: resolved.action.clone(),
assume_yes: cli.yes,
};
let auth = authorize(&confirmation, &resolved.render(), "install")?;
// Bind approval to the reviewed plan and revalidate before any mutation.
let current = match install::revalidate(exec, &cli.root, &resolved) {
Ok(current) => current,
Err(e) => {
return Err(
format!("the reviewed plan changed before execution ({e}); review again").into(),
)
}
};
if current != resolved.approval_digest() {
return Err(
"the reviewed plan changed materially before execution; re-run and review again".into(),
);
}
let described = format!(
"install {} via {} ({})",
resolved.request.application,
resolved.candidate.backend.as_str(),
resolved.source.as_str()
);
// Record before mutation: an interrupted run leaves a visible in-progress
// record rather than a missing one.
let record = TransactionRecord {
id: 0,
created_unix: now_unix(),
origin: "sys".into(),
summary: described.clone(),
actions: vec![described.clone()],
result: "in progress".into(),
snapshot: None,
digest: Some(resolved.approval_digest()),
outcomes: Vec::new(),
};
let id = transaction::begin(exec, &cli.root, record)?;
let outcome = match actions::execute(exec, &resolved.action, Some(&auth), &cli.root) {
Ok(outcome) => outcome,
Err(e) => {
let detail = e.to_string();
let _ = transaction::finish(
exec,
&cli.root,
id,
format!("failed: {detail}"),
None,
vec![TransactionOutcome::failed(
described.clone(),
detail.clone(),
)],
);
return Err(format!("installation failed: {detail}").into());
}
};
if let Some(snapshot) = &outcome.snapshot {
println!("protective snapshot: {snapshot}");
}
println!("{}", outcome.output);
match install::verify_installed(exec, &cli.root, &resolved) {
Ok(verification) => {
println!("{verification}");
transaction::finish(
exec,
&cli.root,
id,
"ok",
outcome.snapshot.clone(),
vec![TransactionOutcome::completed(described.clone())],
)?;
Ok(())
}
Err(e) => {
let detail = e.to_string();
transaction::finish(
exec,
&cli.root,
id,
format!("verify failed: {detail}"),
outcome.snapshot.clone(),
vec![TransactionOutcome::completed(described.clone())],
)?;
Err(format!("the install command completed but verification failed: {detail}").into())
}
}
}
/// Bounded system facts for the assistant: hardware, selected profile and /// Bounded system facts for the assistant: hardware, selected profile and
/// measured compile times. No personal files, credentials or command history. /// measured compile times. No personal files, credentials or command history.
fn gather_facts(exec: &Exec) -> SystemFacts { fn gather_facts(exec: &Exec) -> SystemFacts {
let config = InstallConfig::default(); let config = load_installed_config(&exec.root);
let hardware = probe::probe_hardware(exec.runner.as_ref()); let hardware = probe::probe_hardware(exec.runner.as_ref());
let history = phoebus_core::load_history(&exec.root.join("var/lib/phoebus/compile-times.tsv")); let history = phoebus_core::load_history(&exec.root.join("var/lib/phoebus/compile-times.tsv"));
let binhost = exec.root.join("etc/portage/binrepos.conf").exists(); let binhost = exec.root.join("etc/portage/binrepos.conf").exists();
SystemFacts::from_system(&config, &hardware, &history, binhost, None) let mut facts = SystemFacts::from_system(&config, &hardware, &history, binhost, None);
// Add bounded, read-only environment facts beyond the static config:
// real free space, Wayland, the lanes that are actually usable, saved
// preferences and recovery capability. These are the same facts the
// deterministic selector uses, so the AI and the resolver agree.
let hw = chooser::hardware_facts(exec, &exec.root);
facts.storage_free_mib = hw.storage_free_mib;
facts.wayland = hw.wayland;
facts.available_backends = hw
.available_backends
.iter()
.map(|b| b.as_str().to_string())
.collect();
let prefs = chooser::load_preferences(&exec.root);
facts.saved_preferences = prefs
.per_app
.iter()
.map(|(app, backend)| (app.clone(), backend.as_str().to_string()))
.collect();
facts.recovery_snapshots = exec
.root
.join(phoebus_executor::snapshot::SNAPSHOT_DIR)
.is_dir();
facts
} }
fn load_installed_ai_config(root: &Path) -> Option<phoebus_core::AiConfig> { fn load_installed_ai_config(root: &Path) -> Option<phoebus_core::AiConfig> {
@ -366,6 +777,12 @@ fn run_ask(
exec: &Exec, exec: &Exec,
instruction: &str, instruction: &str,
) -> std::result::Result<(), Box<dyn std::error::Error>> { ) -> std::result::Result<(), Box<dyn std::error::Error>> {
// An installation request through `sys ask` uses the same shared workflow
// (AI investigation + deterministic validation) as `sys install`.
if let Some(application) = parse_install_text(instruction) {
return run_install(cli, exec, &application, backend_flag(cli));
}
let facts = gather_facts(exec); let facts = gather_facts(exec);
let conf = load_installed_ai_config(&cli.root); let conf = load_installed_ai_config(&cli.root);
let backend = resolve_backend(cli, conf.as_ref()); let backend = resolve_backend(cli, conf.as_ref());
@ -536,6 +953,7 @@ fn run_ask(
Some((action, detail)) => format!("failed: {action}: {detail}"), Some((action, detail)) => format!("failed: {action}: {detail}"),
}; };
let record = TransactionRecord { let record = TransactionRecord {
id: 0,
created_unix: now_unix(), created_unix: now_unix(),
origin: "assistant".into(), origin: "assistant".into(),
summary: plan.summary.clone(), summary: plan.summary.clone(),

View file

@ -736,6 +736,16 @@ impl Installer {
} }
} }
// 2b. Persist the non-secret installation configuration so the
// installed `sys` loads the real settings (desktop, filesystem,
// package policy, groups) instead of assuming defaults. There are no
// secrets in `InstallConfig`; passphrases are handled separately.
if let Ok(toml_str) = self.config.to_toml_string() {
self.exec
.target()
.write("etc/phoebus/install.toml", toml_str)?;
}
// 3. Rewrite the desktop entry point last so it cannot be shadowed by an // 3. Rewrite the desktop entry point last so it cannot be shadowed by an
// 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)?;

View file

@ -151,6 +151,110 @@ fn effective_uid_is_root() -> bool {
.unwrap_or(false) .unwrap_or(false)
} }
#[test]
fn conflicting_backend_flags_are_rejected_by_the_cli() {
let out = sys()
.args(["--flatpak", "--nix", "install", "some-app"])
.output()
.expect("run sys");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("cannot be used with")
|| stderr.contains("conflict")
|| stderr.contains("not allowed"),
"stderr: {stderr}"
);
}
#[test]
fn a_backend_flag_without_an_install_is_refused() {
let out = sys()
.args(["--flatpak", "history"])
.output()
.expect("run sys");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("only apply to"), "stderr: {stderr}");
}
#[test]
fn an_explicit_backend_never_falls_back_to_another_lane() {
// No Portage on this host, so an explicit `--portage` install must fail
// with an explanation and must not try Flatpak/snap/anything else.
if effective_uid_is_root() {
return;
}
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(["install", "some-app", "--portage"])
.output()
.expect("run sys");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("cannot satisfy") || stderr.contains("no real candidate"),
"stderr: {stderr}"
);
}
#[test]
fn an_unqualified_install_without_a_model_offers_options_and_installs_nothing() {
if effective_uid_is_root() {
return;
}
let root = tempfile::tempdir().expect("temp root");
let empty = tempfile::tempdir().expect("empty PATH");
let out = sys()
.env("PATH", empty.path())
.env("PHOEBUS_AI_PROVIDER", "none")
.env("PHOEBUS_AI_BACKEND", "direct")
.arg("--root")
.arg(root.path())
.args(["install", "firefox"])
.output()
.expect("run sys");
assert!(
!out.status.success(),
"an unqualified install must not proceed without a model"
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("No connected model") || stderr.contains("no AI provider"),
"stderr: {stderr}"
);
assert!(
stderr.contains("--flatpak") && stderr.contains("--portage"),
"the offer must name the explicit backends: {stderr}"
);
// Nothing may have been installed or executed.
assert!(!root
.path()
.join("var/lib/phoebus/transactions.toml")
.exists());
}
#[test]
fn the_help_lists_every_backend_flag() {
let out = sys().arg("--help").output().expect("run sys");
assert!(out.status.success());
let stdout = String::from_utf8_lossy(&out.stdout);
for flag in [
"--portage",
"--flatpak",
"--nix",
"--snap",
"--appimage",
"--ebuild",
] {
assert!(stdout.contains(flag), "help is missing {flag}");
}
}
#[test] #[test]
fn choose_never_invents_a_candidate() { fn choose_never_invents_a_candidate() {
// Depending on the host, a lane may or may not be resolvable. Either way the // Depending on the host, a lane may or may not be resolvable. Either way the

View file

@ -47,7 +47,7 @@ echo "=== INSTALLER VERSION ==="
echo "=== DISKS BEFORE ===" echo "=== DISKS BEFORE ==="
lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINTS
/tmp/phoebus-installer --config /tmp/test.conf --install --yes \ /tmp/phoebus-installer --config /tmp/test.conf --install --yes --no-ai \
--luks-passphrase-file /tmp/luks.pw --user-password-file /tmp/user.pw --luks-passphrase-file /tmp/luks.pw --user-password-file /tmp/user.pw
rc=$? rc=$?
echo "===INSTALL-RC=$rc===" echo "===INSTALL-RC=$rc==="

View file

@ -0,0 +1,70 @@
#!/bin/bash
# Guest-side VM verification for the AI-first installation workflow.
#
# Boots the reference Gentoo LiveGUI ISO and exercises `sys install` through
# the deterministic CLI and the read-only investigation surface. The live medium
# ships no Portage tree (it syncs during install), so the explicit install step
# runs only when a tree is already present; otherwise it is skipped and the
# read-only workflow checks are the evidence. A real install journey runs on an
# *installed* target (see docs/HANDOFF.md).
set -u
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
BASE="${PHOEBUS_BASE_URL:-http://10.0.2.2:8000}"
PKG="${SYS_CHECK_PACKAGE:-app-misc/hello}"
echo "===LIVE-SYS-START==="
cd /tmp || exit 1
if ! curl -fsSL "$BASE/sys" -o /tmp/sys; then
echo "===SYS-FETCH-FAIL==="; poweroff -f; exit 1
fi
chmod 0755 /tmp/sys
echo "--- version ---"
/tmp/sys --version
echo "--- sync the Portage tree (the live medium ships none) ---"
if timeout 1500 emerge --sync --quiet >/tmp/sync.log 2>&1; then
echo "sync-ok"
else
echo "sync-failed rc=$?; tail:"; tail -5 /tmp/sync.log
fi
echo "--- conflicting flags must be rejected ---"
/tmp/sys install firefox --flatpak --nix
echo "conflict-rc=$?"
echo "--- unqualified install with no model must not install ---"
PHOEBUS_AI_PROVIDER= PHOEBUS_AI_BACKEND=direct /tmp/sys install "$PKG"
echo "no-model-rc=$?"
echo "--- check_backend ---"
/tmp/sys --action '{"action":"check_backend","backend":"portage-source"}'
echo "--- discover_candidates ---"
/tmp/sys --action "{\"action\":\"discover_candidates\",\"query\":\"$PKG\"}"
echo "--- explicit Portage install (deterministic, no model) ---"
if [ -d /var/db/repos/gentoo/profiles ]; then
/tmp/sys -y install "$PKG" --portage
echo "portage-install-rc=$?"
echo "--- verify in the package database ---"
ls -d /var/db/pkg/app-misc/hello-* 2>&1
else
echo "skip: the live medium ships no Portage tree (sync took too long)"
echo "portage-install-rc=skipped"
fi
echo "--- history ---"
/tmp/sys history
if [ -d /var/db/pkg/app-misc ]; then
echo "--- remove to leave the live medium clean ---"
/tmp/sys -y remove "$PKG"
echo "remove-rc=$?"
fi
echo "===LIVE-SYS-DONE==="
sync
echo "===INSTALL-RC=0==="
poweroff -f
echo "===POWEROFF==="

View file

@ -22,6 +22,7 @@ by `PHOEBUS_VM_DISKS` (default `$PHOEBUS_VM_STATE/disks`); block devices,
Results are structured and the exit status is nonzero on failure. Results are structured and the exit status is nonzero on failure.
""" """
import os import os
import re
import sys import sys
import pexpect import pexpect

View file

@ -96,6 +96,41 @@ else
report choose FAIL "unexpected output: $(head -c 200 "$WORK/choose.err")" report choose FAIL "unexpected output: $(head -c 200 "$WORK/choose.err")"
fi fi
# --- AI-first installation workflow (read-only cases) ---------------------
# Conflicting backend flags must be rejected by the CLI.
"$SYS" install firefox --flatpak --nix >"$WORK/conflict.out" 2>"$WORK/conflict.err"
if [[ $? -ne 0 ]] && grep -qi "cannot be used with\|conflict\|not allowed" "$WORK/conflict.err"; then
report install-flag-conflict PASS "rejected"
else
report install-flag-conflict FAIL "$(head -c 160 "$WORK/conflict.err")"
fi
# A backend flag without an install is refused.
"$SYS" --flatpak history >"$WORK/flag.out" 2>"$WORK/flag.err"
if [[ $? -ne 0 ]] && grep -q "only apply to" "$WORK/flag.err"; then
report install-flag-alone PASS "refused"
else
report install-flag-alone FAIL "$(head -c 160 "$WORK/flag.err")"
fi
# An unqualified install with no provider must offer the explicit commands and
# install nothing.
PHOEBUS_AI_PROVIDER= PHOEBUS_AI_BACKEND=direct \
"$SYS" install unused-package-xyz >"$WORK/noai.out" 2>"$WORK/noai.err"
if [[ $? -ne 0 ]] && grep -q -- "--flatpak" "$WORK/noai.err"; then
report install-no-model-offer PASS "no model: deterministic offer shown"
else
report install-no-model-offer FAIL "$(head -c 200 "$WORK/noai.err")"
fi
# Read-only investigation returns structured evidence.
"$SYS" --action '{"action":"check_backend","backend":"flatpak"}' >"$WORK/be.out" 2>"$WORK/be.err"
if grep -q '"backend"' "$WORK/be.out"; then
report investigate-check-backend PASS "$(head -c 120 "$WORK/be.out" | tr '\n' ' ')"
else
report investigate-check-backend FAIL "$(head -c 160 "$WORK/be.err")"
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}"