Compare commits

...

10 commits

Author SHA1 Message Date
8dbf624046 docs: pin the handoff to this session's verification commit
Some checks are pending
ci / test (push) Waiting to run
2026-09-20 06:59:18 -07:00
b2f5181f7f docs: record the desktop VM session and AI guided-path verification
Add the detached-boot desktop verification (socket wait, polkit agent,
helper reaping) and pin the lockfile for the new phoebus-ai dependency.
2026-09-20 06:59:01 -07:00
c6665e550a fix(ai): refuse proposals that weaken required settings
Deterministic review now rejects encryption=none, filesystem=ext4 and the
aggressive kernel profile, so the LUKS2/Btrfs/stability posture cannot be
traded for convenience. A live provider that returns an invalid proposal is
reported and the installer continues with the proven defaults (the explicit
--ai-proposal-file test path still fails loudly).
2026-09-20 05:04:12 -07:00
b120c1e5e4 docs: record AI guidance, desktop reliability and snapshot verification
Update the status matrix, roadmap, changelog and handoff; add the WS4/WS3 VM
evidence and a concise real-VT desktop test procedure.
2026-09-20 05:03:37 -07:00
a20e064680 fix(update): keep fetched distfiles when binary prebuild is skipped
emerge --buildpkgonly refuses while dependencies still need merging, which
is normal for an out-of-date system. Record that as Ready with the fetched
distfiles and the Portage reason instead of a hard Failure, and include the
redacted stderr tail in the state note. The VM harness check timeout is now
configurable.
2026-09-20 05:00:45 -07:00
035826e0f9 test(desktop): functionally verify phoebus-session startup and cleanup
Run the generated session script against stub dwl/helper binaries: helpers
must start only after the Wayland socket exists, the polkit agent must start,
and every helper must be reaped when the compositor exits. A compositor that
dies before creating the socket fails the session loudly.
2026-09-20 05:00:45 -07:00
b45e61e361 feat(ai): guided AI optimization with DeepSeek/OpenAI providers
Add an OpenAI-compatible provider layer (DeepSeek, OpenAI and a test
transport) that sends only bounded system facts and injects the API key via a
curl config on stdin, never in argv, config or logs. Extend the typed proposal
schema with scoped package.use, build jobs and binary-package preference; every
change now needs a non-empty reason and duplicates are rejected. Wire
--ai/--ai-proposal-file/--ai-facts into the CLI and add provider selection to
the TUI. Deterministic validation and review are unchanged: the model never
reaches the executor and the no-AI path keeps working.
2026-09-20 04:47:11 -07:00
fcda004834 perf(portage): reduce forced USE overrides and derive the signed binhost
Drop the unused installkernel uki flag (BLS uses uki_generator=none), remove
the empty wireplumber line and the duplicate pipewire entry, and add scoped
package.use plus explicit build jobs to the typed config. The binhost URI is
now derived from the selected profile when unset. No change weakens signature
verification or enables ~amd64.
2026-09-20 04:41:52 -07:00
24b7259e56 fix(desktop): make phoebus-session race-free and reap helpers
The session script started waybar/mako/swaybg before dwl created the
Wayland socket and never started the polkit agent. It now starts dwl first,
waits for wayland-0, establishes a session bus and runtime dir, starts the
polkit authentication agent, and kills helpers when the compositor exits.
2026-09-20 04:40:08 -07:00
e82aaba5fb fix(executor): fail closed when a protective snapshot cannot be created
High-risk sys actions now create their protective snapshot inside
actions::execute and abort if the .snapshots subvolume exists but the snapshot
fails, instead of warning and mutating anyway. Corrupt snapshot history is
surfaced as an error rather than being silently treated as empty.
2026-09-20 04:39:23 -07:00
29 changed files with 2438 additions and 139 deletions

View file

@ -15,6 +15,38 @@ Format: Keep a Changelog. Dates are UTC.
`CHANGELOG.md`, and the top-level `AGENTS.md`.
- `.gitignore` covering the ISO, build output, transcripts and secrets.
## 2026-09-20 — AI guidance, desktop reliability, snapshots
### Added
- AI-assisted install guidance: an OpenAI-compatible provider layer for
**DeepSeek** and **OpenAI** plus a test transport
(`phoebus-ai::provider`), credential loading and a curl transport that keeps
the API key out of argv, config and logs (`phoebus-executor::ai`), and CLI
flags `--ai`, `--ai-provider`, `--ai-model`, `--ai-api-key-file`,
`--ai-proposal-file`, `--ai-facts`. The TUI offers
DeepSeek/ChatGPT/without-AI.
- Typed proposal extensions: scoped `package.use`, explicit build jobs and
binary-package preference. Every proposal now requires a non-empty reason and
duplicate/conflicting changes are rejected before anything is applied.
- `sys` history and update preparation are VM-verified on a Btrfs install.
### Changed
- `phoebus-session` now starts `dwl` first, waits for the Wayland socket before
launching waybar/mako/swaybg, establishes `XDG_RUNTIME_DIR` and a session bus,
starts the polkit authentication agent, and reaps helpers on logout.
- Portage policy: the unused `installkernel uki` flag is no longer forced, the
duplicate/empty PipeWire/WirePlumber lines are gone, and the signed binhost is
derived from the selected profile when unset.
- Update preparation records a successful distfile fetch as ready even when
`--buildpkgonly` is skipped because dependencies must be merged first, and the
state note now includes the redacted Portage reason.
### Fixed
- A high-risk `sys` action now creates its protective snapshot inside
`actions::execute` and **fails closed** if the `.snapshots` subvolume exists
but the snapshot cannot be created; corrupt snapshot history is surfaced
instead of being hidden as empty.
## 2026-09-20 — Retire the Bash installer (migration Phases 0–4)
### Added

View file

@ -88,7 +88,35 @@ grim /tmp/shot.png # proves the compositor renders
```
On a real machine the installer writes `/usr/local/bin/phoebus-session`
(waybar + mako + swaybg + dwl).
(dwl + waybar + mako + swaybg + the polkit agent).
### Physical VT / real-seat check (needs a person)
The serial harness has no logind seat, so this must be done on real hardware or
a seat-providing VM. From a text VT (e.g. `Ctrl+Alt+F3`), log in and run:
```sh
/usr/local/bin/phoebus-session
```
Check, in order:
1. `dwl` starts and the screen shows the compositor (no `Failed to start a DRM
session`).
2. `waybar` and `mako` appear only after the compositor is up (they must not
log a failed Wayland connection).
3. Open a terminal: `kitty`. Run an X11 app to exercise XWayland (e.g.
`xterm` or `env -u WAYLAND_DISPLAY kitty` if no X app is installed).
4. Trigger a privilege prompt (e.g. `pkexec true` or a polkit-gnome dialog) and
confirm the authentication agent appears.
5. Log out (`Mod+Shift+e` for dwl). Confirm `waybar`, `mako`, `swaybg` and the
polkit agent are gone (`pgrep -a 'waybar|mako|swaybg|polkit-gnome'` prints
nothing) and that the session returns to the VT login.
6. Reboot and confirm the same result.
Record the result (date, kernel, GPU, pass/fail per step) in
`docs/VM-BOOT-VERIFICATION.md`. A headless wlroots session is not physical-seat
verification.
## Inspecting the reference ISO without booting

View file

@ -3,31 +3,41 @@
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.
- **Last updated:** commit `fc64793` (2026-09-20)
- **Current focus:** the Bash installer is retired (migration Phases 0–4, see
`docs/BASH-MIGRATION.md`); `installer-rs/` is the only installer.
- **Last verified:** static Rust binary, full encrypted UEFI VM install +
detached boot (`docs/VM-BOOT-VERIFICATION.md`); desktop stack and Flatpak
verified headless.
- **Last updated:** commit `b2f5181` (2026-09-20)
- **Current focus:** four workstreams — AI-assisted install guidance, desktop
session reliability, signed-binary reuse, and snapshots/safe updates.
- **Last verified:** static Rust binary install + detached boot
(`docs/VM-BOOT-VERIFICATION.md`); in this session additionally: a full dwl
desktop install + detached boot with the session's helpers waiting for the
Wayland socket, the polkit agent running and all helpers reaped on logout;
`sys` snapshot/history and update preparation on an installed Btrfs VM; and
the AI guided path (valid/invalid/malicious/conflicting/no-AI) by fixtures.
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222).
## Next actions (in order)
1. **Physical-seat desktop**: run `phoebus-session`/dwl on a real VT and verify
kitty, wofi, XWayland, the polkit agent, logout and reboot interactively.
2. **Desktop binary strategy**: match desktop USE to a signed binhost (or
publish one) to stop compiling ~26 minutes of desktop packages.
3. **Snapshots + safe updates end-to-end**: prove `sys` snapshot and
`prepare-updates` on an installed system, then implement and test rollback
before wiring `sys undo`.
1. **Physical-seat desktop**: run `/usr/local/bin/phoebus-session` on a real VT
and check kitty, XWayland, the polkit agent, logout/reap and reboot
(`docs/DEVELOPMENT.md` -> "Physical VT / real-seat check").
2. **Matching signed binhost**: the official Gentoo binhost is OpenRC/hardened,
so systemd/desktop packages compile from source. Publish (or point at) a
systemd/desktop binhost to raise binary reuse; verify with `emerge -pv`.
3. **Rollback gate**: implement Btrfs default-subvolume + ESP handling and pass
a detached-boot test before exposing `sys undo`.
4. **Live AI provider call**: exercise DeepSeek/OpenAI with a real 0600 key
file; the path is currently fixture-verified only.
5. **Desktop graphical login**: exercise a real logind seat.
## Known blockers / risks
- No live DeepSeek/OpenAI call has been made (no key in this environment).
- No Forgejo Actions runner is known to exist; `.forgejo/workflows/ci.yml`
only runs once one is registered.
- Desktop graphical login has not been exercised with a real logind seat.
- Desktop graphical login / physical seat has not been exercised; the serial
VM has no logind seat.
- NVIDIA is not verified on hardware.
- Rollback is not implemented (by design, gated).
## Environment notes
@ -36,6 +46,7 @@ commit it. It should be short and current; use `git log` for detail.
- Forgejo token for API tasks: `~/.config/phoebus/forgejo.token` (0600).
- The VM harness disks are disposable qcow2 files on `/` (not `/tmp`, which is
a small tmpfs on the dev host); never point `DISK` at `/dev/*`.
- The VM harness honours `CHECKS_TIMEOUT` for long guest checks.
## Definition of a good stopping point

View file

@ -10,29 +10,33 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**.
| 3 | Port the deterministic core | Done | `phoebus-core` (config, plan, policy, validation, models) |
| 4 | Port the destructive backend | Done | `phoebus-executor` (storage, LUKS2, Btrfs, Portage, boot, users, services) |
| 5 | **Rust VM boot parity** | Done | Full encrypted UEFI install + boot, zero failed units, 10.7 s |
| 6 | Finish the desktop | Partial | dwl/waybar/mako/swaybg/pipewire verified headless; physical seat + interactive login pending |
| 6 | Finish the desktop | Partial | session script race-free + polkit + helper cleanup (functional test); headless compositor verified; physical seat + interactive login pending |
| 7 | Finish Flatpak | Partial | `flatpak 1.18.1` installed, flathub configured; no app installed yet |
| 8 | Instrument source/binary policy | Done | measured compile times harvested from `emerge.log` (326 entries) |
| 9 | Background update preparation | Partial | `--fetchonly` + `--buildpkgonly` implemented and unit-tested; not VM-tested |
| 10 | Snapshots / rollback | Partial | snapshot create + history done; rollback not implemented |
| 11 | AI privilege and privacy architecture | Partial | typed actions + enforced privacy boundary; OS sandbox not implemented |
| 12 | `sys` operations | Partial | history, enable/disable service, inspect, install, prepare-updates |
| 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit |
| 10 | Snapshots / rollback | Partial | snapshot create + history VM-verified on Btrfs; rollback not implemented |
| 11 | AI privilege and privacy architecture | Partial | typed actions + enforced privacy boundary + guided DeepSeek/OpenAI proposal review; OS sandbox not implemented |
| 12 | `sys` operations | Partial | history, enable/disable, inspect, install, prepare-updates VM-verified |
| 13 | Kernel optimization policy | Later | conservative fragments only; SAFE/OPTIMIZED/AGGRESSIVE selection exists |
| 14 | ISO / release pipeline | Partial | manifest/verify/assemble-plan tooling; no scheduling/publish/smoke test |
| 15 | Recovery environment | Later | recovery BLS entry generated; full recovery image not built |
| — | Rust TUI | Partial | ratatui UI with plan/ERASE; not yet the default on all paths |
| — | Rust TUI | Partial | ratatui UI with plan/ERASE and AI provider selection; not yet the default on all paths |
| — | AI-guided install optimization | Partial | DeepSeek/OpenAI providers, evidence-gated typed review, TUI opt-in; fixture-verified, no live call |
| — | Git workflow + agent guide | Done | this `docs/` set, `.githooks/`, `scripts/` |
## Immediate next steps
1. **Physical-seat desktop**: run `phoebus-session`/dwl on a real VT (or a
`seatd`-backed session) and verify kitty, wofi, XWayland, the polkit agent,
logout and reboot interactively.
logout and reboot interactively (`docs/DEVELOPMENT.md`).
2. **Desktop binary strategy**: match the desktop USE set to a signed binhost
(or publish one) so desktop installs stop compiling ~26 minutes of packages.
3. **Snapshots and safe updates end-to-end**: prove `sys` snapshot +
`prepare-updates` on an installed system, then implement and test rollback
before wiring `sys undo`.
The official binhost is OpenRC/hardened; a systemd/desktop host is needed.
3. **Rollback as a safety gate**: implement Btrfs default-subvolume + ESP
handling and pass a detached-boot test before exposing `sys undo`
(snapshot/history/prepare-updates are now VM-verified).
4. **Live AI provider call**: exercise DeepSeek/OpenAI with a real 0600 key
file; the guided path is currently fixture-verified only.
## Later

View file

@ -56,17 +56,19 @@ on the install path (Bash migration Phase 2, see
| Rust VM boot parity | yes | yes | yes | no |
| Rust TUI | yes | yes | smoke test | no |
| Desktop profile (dwl/waybar/mako/swaybg) | yes | partial | headless only | no |
| Desktop session script (socket wait, polkit, cleanup) | yes | yes | functional test (stubs) | no |
| PipeWire/WirePlumber | yes | no | headless (`wpctl`) | no |
| Flatpak + flathub | yes | no | installed + remote | no |
| XWayland / polkit agent / kitty / wofi | yes | no | installed, not launched | no |
| Package policy + measured history | yes | yes | yes (326 entries) | no |
| Background update preparation | yes | yes | no | no |
| Btrfs snapshots + history | yes | yes | no | no |
| Background update preparation | yes | yes | yes (fetch; buildpkgonly skipped) | no |
| Btrfs snapshots + history | yes | yes | yes | no |
| Btrfs rollback | no | no | no | no |
| AI typed proposals | yes | yes | no | n/a |
| AI privacy boundary | yes | yes | no | n/a |
| AI typed proposals + evidence review | yes | yes | fixture end-to-end | n/a |
| AI guided install (DeepSeek/OpenAI) | yes | yes | fixture path only (no live call) | n/a |
| AI privacy boundary (facts only) | yes | yes | no | n/a |
| AI OS sandbox | no | no | no | no |
| `sys` verbs | yes | yes | no | no |
| `sys` verbs | yes | yes | yes | no |
| OpenCode pinned bootstrap | yes | yes | no | n/a |
| Release manifest/verify | yes | yes | no | n/a |
| NVIDIA proprietary | architecture only | no | no | no |
@ -89,5 +91,14 @@ on the install path (Bash migration Phase 2, see
signing or atomic publish.
- The desktop transaction compiles heavily because desktop USE does not match
the signed binhost (~26 min for the desktop set on 8 vCPUs in the test VM).
The official Gentoo binhost is OpenRC/hardened, so a systemd system can only
reuse binaries for packages whose USE matches; the policy still requests
signed binaries where it can. Publishing a matching binhost is future work.
- **Live AI provider calls are not verified.** DeepSeek/OpenAI requests are
built and reviewed by fixtures (`phoebus-ai::provider::TestTransport`) and the
curl transport is covered by a recording runner; no call was made with a real
key.
- The installer rebuilds `sys-apps/systemd` from source because
boot/policykit/cryptsetup USE differ from the binhost.
- `sys undo` is intentionally not implemented: rollback needs default-subvolume
and ESP handling plus a detached-boot test, which is a separate safety gate.

View file

@ -209,6 +209,79 @@ Boot with the ISO detached (`serial-driver.py boot`):
This satisfies the Phase 2 exit gate of `docs/BASH-MIGRATION.md`: the only
proven boot path no longer depends on the retired Bash installer.
## Snapshots and safe updates (four-workstream session)
Verified on the installed Btrfs system from the static-binary harness, driving
the new `sys` binary fetched into the guest:
- `sys history` before -> `no transaction history`.
- `sys -y --action '{"action":"create_snapshot","operation":"vm test"}'` ->
`protective snapshot: @-20260920T114917-vm-test`.
- `sys history` after -> `@-20260920T114917-vm-test Committed vm test`.
- `btrfs subvolume list /` shows `@snapshots/@-20260920T114917-vm-test` as a
real subvolume (read-only snapshot).
- `sys -y prepare-updates` fetched distfiles successfully; `--buildpkgonly` was
refused by Portage with `--buildpkgonly requires all dependencies to be
merged`, which the installer now records as `status: Ready` with the reason
(`distfiles fetched; binary prebuild skipped: ...`) instead of a hard failure.
- `sys inspect-updates` reports the state and timestamp.
Unit regression tests cover the failure paths that a VM cannot easily force:
corrupt snapshot history is an error, and a high-risk action aborts when the
protective snapshot fails.
## Desktop session on an installed VM
A full dwl desktop install was built with the static Rust binary
(`DESKTOP_PROFILE=dwl`, `FLATPAK=no`) and booted with the ISO detached:
`INSTALL_RC=0`, all stages, `NO_SECRET_LEAK`, `systemctl is-system-running` ->
`running`, `0 failed units`.
Running the installed `/usr/local/bin/phoebus-session` under the headless
wlroots backend (the serial VM has no logind seat):
- the `wayland-0` socket is created before any helper starts;
- after startup the process tree is `dwl`, `waybar`, `mako`,
`swaybg -c #1e1e2e` and `/usr/libexec/polkit-gnome-authentication-agent-1`
(the polkit agent, which the previous script never started);
- dwl reports the `HEADLESS-1` output;
- after `dwl` exits, **all session processes are reaped**.
Installed and on `PATH`: `dwl`, `waybar`, `mako`, `swaybg`, `kitty`, `wofi`,
`Xwayland`. The polkit agent lives at
`/usr/libexec/polkit-gnome-authentication-agent-1`; the session script's
fallback finds it because it is not on `PATH`.
This is headless verification. A physical VT / real logind seat remains to be
exercised interactively (`docs/DEVELOPMENT.md` -> "Physical VT / real-seat
check").
## Signed binary reuse analysis
The desktop transaction's installer log (`emerge` grouping) shows the policy
already requests signed binaries for the expensive set:
- source group: `sys-fs/cryptsetup sys-fs/btrfs-progs`;
- binary groups: base tools, `gentoo-kernel-bin`/firmware, and the dwl/waybar/
wofi/mako/sway*/gtk-layer-shell/xwayland set.
The desktop install in this session took ~1h49m wall time (12:01–13:50 UTC) on
8 vCPUs. Most of that is Portage falling back to source because the OpenRC/
hardened binhost cannot satisfy the systemd/desktop USE set, even though the
policy requested binaries. Two comparable data points are now recorded: the
base-only install took ~44 min and the desktop install ~1h49m. The code changes
here remove forced flags but cannot raise reuse without a matching binhost, so
no new time saving is claimed.
The remaining source builds are caused by the **official Gentoo binhost being
built for the OpenRC/hardened profile** (`PROFILE: default/linux/amd64/17.0/
hardened`), which cannot satisfy a systemd/desktop USE set. The safe changes
made here are: stop forcing the unused `installkernel uki` flag, remove the
duplicate PipeWire and empty WirePlumber `package.use` lines, and derive the
binhost URI from the selected profile when it is not set. Signature
verification remains enabled. Publishing a matching systemd/desktop binhost is
the remaining step; no time estimate is claimed beyond the recorded ~26 min.
## Known remaining work
- The graphical session was verified with the **headless** wlroots backend

View file

@ -523,6 +523,7 @@ name = "phoebus-installer"
version = "0.1.0"
dependencies = [
"clap",
"phoebus-ai",
"phoebus-core",
"phoebus-executor",
"phoebus-tui",

View file

@ -7,9 +7,10 @@
//! step performed by the deterministic backend.
pub mod privacy;
pub mod provider;
use phoebus_core::config::{
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy,
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy, PackageUse,
};
use phoebus_core::validate;
use serde::{Deserialize, Serialize};
@ -22,31 +23,89 @@ pub enum AiError {
UnsupportedVersion(u32),
#[error("change rejected: {0}")]
Rejected(String),
#[error("AI provider unavailable: {0}")]
ProviderUnavailable(String),
#[error("AI provider error: {0}")]
Provider(String),
#[error("model context would carry personal data: {0}")]
PrivateData(String),
}
/// A versioned, closed set of configuration changes.
/// A versioned, closed set of configuration changes, each with a rationale.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AiProposal {
pub version: u32,
pub changes: Vec<ProposedChange>,
/// One entry per change, naming the action and giving the evidence/reason.
#[serde(default)]
pub rationale: Vec<Rationale>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Why a change was proposed. Deterministic code requires a non-empty reason
/// for every accepted change.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Rationale {
pub action: String,
pub reason: String,
#[serde(default)]
pub evidence: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum ProposedChange {
SetHostname { value: String },
SetTimezone { value: String },
SetLocale { value: String },
SetKeymap { value: String },
SetUsername { value: String },
SetTargetDisk { value: String },
SetFilesystem { value: Filesystem },
SetEncryption { value: Encryption },
SetKernelProfile { value: KernelProfile },
SetPackagePolicy { value: PackagePolicy },
SetDesktopProfile { value: DesktopProfile },
SetFlatpak { value: bool },
SetHostname {
value: String,
},
SetTimezone {
value: String,
},
SetLocale {
value: String,
},
SetKeymap {
value: String,
},
SetUsername {
value: String,
},
SetTargetDisk {
value: String,
},
SetFilesystem {
value: Filesystem,
},
SetEncryption {
value: Encryption,
},
SetKernelProfile {
value: KernelProfile,
},
SetPackagePolicy {
value: PackagePolicy,
},
SetDesktopProfile {
value: DesktopProfile,
},
SetFlatpak {
value: bool,
},
/// Prefer signed binary packages (still signature-verified).
SetBinaryPackages {
value: bool,
},
/// Explicit Portage `MAKEOPTS -j` value (capped by available memory later).
SetBuildJobs {
value: u32,
},
/// One scoped `package.use` flag for one atom.
SetPackageUse {
atom: String,
flag: String,
enabled: bool,
},
}
impl ProposedChange {
@ -64,10 +123,67 @@ impl ProposedChange {
ProposedChange::SetPackagePolicy { value } => format!("package policy = {value}"),
ProposedChange::SetDesktopProfile { value } => format!("desktop profile = {value}"),
ProposedChange::SetFlatpak { value } => format!("flatpak = {value}"),
ProposedChange::SetBinaryPackages { value } => {
format!("prefer signed binary packages = {value}")
}
ProposedChange::SetBuildJobs { value } => format!("build jobs = {value}"),
ProposedChange::SetPackageUse {
atom,
flag,
enabled,
} => format!(
"package.use {atom} {}{flag}",
if *enabled { "" } else { "-" }
),
}
}
/// Semantic validation against the current configuration.
/// The stable action name (matches the serde tag).
pub fn action_name(&self) -> &'static str {
match self {
ProposedChange::SetHostname { .. } => "set_hostname",
ProposedChange::SetTimezone { .. } => "set_timezone",
ProposedChange::SetLocale { .. } => "set_locale",
ProposedChange::SetKeymap { .. } => "set_keymap",
ProposedChange::SetUsername { .. } => "set_username",
ProposedChange::SetTargetDisk { .. } => "set_target_disk",
ProposedChange::SetFilesystem { .. } => "set_filesystem",
ProposedChange::SetEncryption { .. } => "set_encryption",
ProposedChange::SetKernelProfile { .. } => "set_kernel_profile",
ProposedChange::SetPackagePolicy { .. } => "set_package_policy",
ProposedChange::SetDesktopProfile { .. } => "set_desktop_profile",
ProposedChange::SetFlatpak { .. } => "set_flatpak",
ProposedChange::SetBinaryPackages { .. } => "set_binary_packages",
ProposedChange::SetBuildJobs { .. } => "set_build_jobs",
ProposedChange::SetPackageUse { .. } => "set_package_use",
}
}
/// A key identifying what this change touches, for conflict detection.
pub fn target_key(&self) -> String {
match self {
ProposedChange::SetHostname { .. } => "system.hostname".into(),
ProposedChange::SetTimezone { .. } => "system.timezone".into(),
ProposedChange::SetLocale { .. } => "system.locale".into(),
ProposedChange::SetKeymap { .. } => "system.keymap".into(),
ProposedChange::SetUsername { .. } => "user.username".into(),
ProposedChange::SetTargetDisk { .. } => "storage.disk".into(),
ProposedChange::SetFilesystem { .. } => "storage.filesystem".into(),
ProposedChange::SetEncryption { .. } => "encryption.mode".into(),
ProposedChange::SetKernelProfile { .. } => "kernel.profile".into(),
ProposedChange::SetPackagePolicy { .. } => "packages.policy".into(),
ProposedChange::SetDesktopProfile { .. } => "desktop.profile".into(),
ProposedChange::SetFlatpak { .. } => "desktop.flatpak".into(),
ProposedChange::SetBinaryPackages { .. } => "packages.binary_packages".into(),
ProposedChange::SetBuildJobs { .. } => "packages.build_jobs".into(),
ProposedChange::SetPackageUse { atom, flag, .. } => {
format!("packages.package_use:{atom}:{flag}")
}
}
}
/// Semantic validation. `package.use` changes are validated with the same
/// rules the configuration uses.
pub fn validate(&self) -> Result<(), String> {
match self {
ProposedChange::SetHostname { value } => validate::validate_hostname(value),
@ -82,6 +198,17 @@ impl ProposedChange {
Err(format!("target disk must be a /dev path: {value}"))
}
}
ProposedChange::SetBuildJobs { value } => {
if (1..=256).contains(value) {
Ok(())
} else {
Err(format!("build jobs must be between 1 and 256: {value}"))
}
}
ProposedChange::SetPackageUse { atom, flag, .. } => {
validate::validate_package_atom(atom)?;
validate::validate_use_flag(flag)
}
_ => Ok(()),
}
}
@ -129,6 +256,29 @@ pub fn apply(
ProposedChange::SetPackagePolicy { value } => config.packages.policy = *value,
ProposedChange::SetDesktopProfile { value } => config.desktop.profile = *value,
ProposedChange::SetFlatpak { value } => config.desktop.flatpak = *value,
ProposedChange::SetBinaryPackages { value } => config.packages.binary_packages = *value,
ProposedChange::SetBuildJobs { value } => config.packages.build_jobs = Some(*value),
ProposedChange::SetPackageUse {
atom,
flag,
enabled,
} => {
let entry = PackageUse {
atom: atom.clone(),
flag: flag.clone(),
enabled: *enabled,
};
if let Some(existing) = config
.packages
.package_use
.iter_mut()
.find(|e| e.atom == *atom && e.flag == *flag)
{
existing.enabled = *enabled;
} else {
config.packages.package_use.push(entry);
}
}
}
applied.push(AppliedChange {
description: change.describe(),
@ -137,6 +287,127 @@ pub fn apply(
Ok(applied)
}
/// A change that passed review, with the model's stated reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewedChange {
pub description: String,
pub reason: String,
pub evidence: Vec<String>,
}
/// The result of reviewing a proposal: the changes that were applied and the
/// rationale behind each.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewOutcome {
pub applied: Vec<ReviewedChange>,
}
impl ReviewOutcome {
/// A compact human-readable summary of accepted changes and reasons.
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str("Accepted AI changes:\n");
if self.applied.is_empty() {
out.push_str(" (none)\n");
}
for change in &self.applied {
out.push_str(&format!(" + {}\n", change.description));
out.push_str(&format!(" reason: {}\n", change.reason));
for item in &change.evidence {
out.push_str(&format!(" evidence: {item}\n"));
}
}
out
}
}
/// Changes that would weaken a required, non-negotiable setting.
///
/// Phoebus is a LUKS2 + Btrfs system; aggressive kernel profiles are
/// speculative. The model may propose these, but a deterministic check refuses
/// them so the proven security posture is never traded for convenience.
fn fixed_policy_violation(change: &ProposedChange) -> Option<String> {
match change {
ProposedChange::SetEncryption {
value: Encryption::None,
} => Some("encryption must remain LUKS2".into()),
ProposedChange::SetFilesystem {
value: Filesystem::Ext4,
} => Some("the filesystem must remain Btrfs".into()),
ProposedChange::SetKernelProfile {
value: KernelProfile::Aggressive,
} => Some("aggressive kernel profiles are not accepted".into()),
_ => None,
}
}
/// Validate a proposal with mandatory evidence, reject conflicts and unsafe
/// changes, and apply it atomically (fail closed). This is the path a guided
/// install uses; the model never reaches the executor without passing it.
pub fn review(config: &mut InstallConfig, proposal: &AiProposal) -> Result<ReviewOutcome, AiError> {
if proposal.version != 1 {
return Err(AiError::UnsupportedVersion(proposal.version));
}
// Every change needs an explicit, non-empty reason.
let reason_for = |change: &ProposedChange| -> Result<&Rationale, AiError> {
proposal
.rationale
.iter()
.find(|r| r.action == change.action_name() && !r.reason.trim().is_empty())
.ok_or_else(|| {
AiError::Rejected(format!(
"{}: missing a non-empty reason",
change.action_name()
))
})
};
// Reject conflicts before applying anything.
let mut seen: Vec<String> = Vec::new();
for change in &proposal.changes {
let key = change.target_key();
if seen.contains(&key) {
return Err(AiError::Rejected(format!("conflicting changes for {key}")));
}
seen.push(key);
}
// Validate everything; a single failure rejects the whole proposal.
for change in &proposal.changes {
if let Some(reason) = fixed_policy_violation(change) {
return Err(AiError::Rejected(format!(
"{}: {reason}",
change.action_name()
)));
}
change.validate().map_err(AiError::Rejected)?;
reason_for(change)?;
}
// Apply only after all checks pass. `apply` repeats validation, which is
// harmless and keeps a single merge implementation.
let applied = apply(config, proposal)?;
let reviewed = proposal
.changes
.iter()
.zip(applied)
.map(|(change, applied)| {
let rationale = proposal
.rationale
.iter()
.find(|r| r.action == change.action_name())
.expect("reason checked above");
ReviewedChange {
description: applied.description,
reason: rationale.reason.clone(),
evidence: rationale.evidence.clone(),
}
})
.collect();
Ok(ReviewOutcome { applied: reviewed })
}
#[cfg(test)]
mod tests {
use super::*;
@ -193,4 +464,128 @@ mod tests {
let text = r#"{"version":1,"changes":[{"action":"set_filesystem","value":"zfs"}]}"#;
assert!(parse_proposal(text).is_err());
}
#[test]
fn review_applies_scoped_package_use_and_build_jobs() {
let text = r#"{
"version": 1,
"changes": [
{"action":"set_build_jobs","value":6},
{"action":"set_binary_packages","value":true},
{"action":"set_package_use","atom":"www-client/firefox","flag":"wayland","enabled":true}
],
"rationale": [
{"action":"set_build_jobs","reason":"16 GiB of RAM","evidence":["memory_mib=16384"]},
{"action":"set_binary_packages","reason":"signed binhost is available","evidence":["binhost=openrc"]},
{"action":"set_package_use","reason":"wayland desktop","evidence":["desktop=dwl"]}
]
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
let outcome = review(&mut config, &proposal).unwrap();
assert_eq!(outcome.applied.len(), 3);
assert_eq!(config.packages.build_jobs, Some(6));
assert!(config.packages.binary_packages);
assert_eq!(config.packages.package_use.len(), 1);
assert_eq!(config.packages.package_use[0].atom, "www-client/firefox");
let rendered = outcome.render();
assert!(rendered.contains("reason:"));
assert!(rendered.contains("evidence:"));
}
#[test]
fn review_rejects_a_change_without_a_reason() {
let text = r#"{
"version": 1,
"changes": [{"action":"set_hostname","value":"box"}],
"rationale": []
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
assert!(matches!(
review(&mut config, &proposal),
Err(AiError::Rejected(_))
));
// Nothing applied.
assert_eq!(config.system.hostname, "phoebus");
}
#[test]
fn review_rejects_conflicting_changes() {
let text = r#"{
"version": 1,
"changes": [
{"action":"set_hostname","value":"one"},
{"action":"set_hostname","value":"two"}
],
"rationale": [
{"action":"set_hostname","reason":"a"},
{"action":"set_hostname","reason":"b"}
]
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
assert!(matches!(
review(&mut config, &proposal),
Err(AiError::Rejected(_))
));
assert_eq!(config.system.hostname, "phoebus");
}
#[test]
fn review_rejects_unsafe_package_use() {
let text = r#"{
"version": 1,
"changes": [
{"action":"set_package_use","atom":"*/*","flag":"*","enabled":true}
],
"rationale": [{"action":"set_package_use","reason":"all"}]
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
assert!(matches!(
review(&mut config, &proposal),
Err(AiError::Rejected(_))
));
assert!(config.packages.package_use.is_empty());
}
#[test]
fn review_refuses_to_weaken_required_settings() {
for (action, value) in [
("set_encryption", "none"),
("set_filesystem", "ext4"),
("set_kernel_profile", "aggressive"),
] {
let text = format!(
r#"{{"version":1,"changes":[{{"action":"{action}","value":"{value}"}}],"rationale":[{{"action":"{action}","reason":"x"}}]}}"#
);
let proposal = parse_proposal(&text).unwrap();
let mut config = InstallConfig::default();
assert!(
matches!(review(&mut config, &proposal), Err(AiError::Rejected(_))),
"{action}={value} must be refused"
);
// The proven defaults are untouched.
assert_eq!(config.encryption.mode, Encryption::Luks2);
assert_eq!(config.storage.filesystem, Filesystem::Btrfs);
assert_eq!(config.kernel.profile, KernelProfile::Optimized);
}
}
#[test]
fn review_requires_a_supported_version() {
let proposal = parse_proposal(r#"{"version":1,"changes":[]}"#).unwrap();
let mut config = InstallConfig::default();
assert!(review(&mut config, &proposal).is_ok());
let bad = AiProposal {
version: 2,
changes: vec![],
rationale: vec![],
};
assert!(matches!(
review(&mut config, &bad),
Err(AiError::UnsupportedVersion(2))
));
}
}

View file

@ -0,0 +1,475 @@
//! Model provider connections.
//!
//! DeepSeek and OpenAI both expose an OpenAI-compatible chat-completions API,
//! so one request/response shape covers both. The provider layer builds the
//! request from a closed set of approved [`SystemFacts`]; the API key is never
//! part of the request and is injected by the transport (see
//! `phoebus-executor::ai`). [`TestTransport`] makes the whole path exercisable
//! without a network.
use std::collections::{BTreeMap, HashMap};
use phoebus_core::config::InstallConfig;
use phoebus_core::hardware::HardwareReport;
use serde::{Deserialize, Serialize};
use crate::privacy::is_forbidden_path;
use crate::{parse_proposal, AiError, AiProposal};
/// The selectable providers. `None` means "continue without AI".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProviderKind {
None,
DeepSeek,
OpenAi,
}
impl ProviderKind {
pub fn as_str(self) -> &'static str {
match self {
ProviderKind::None => "none",
ProviderKind::DeepSeek => "deepseek",
ProviderKind::OpenAi => "openai",
}
}
/// Parse a user-facing provider name (aliases included).
pub fn parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"" | "none" | "no" | "off" | "without" => Some(ProviderKind::None),
"deepseek" => Some(ProviderKind::DeepSeek),
"openai" | "chatgpt" | "gpt" => Some(ProviderKind::OpenAi),
_ => None,
}
}
/// The chat-completions endpoint.
pub fn endpoint(self) -> &'static str {
match self {
ProviderKind::None => "",
ProviderKind::DeepSeek => "https://api.deepseek.com/chat/completions",
ProviderKind::OpenAi => "https://api.openai.com/v1/chat/completions",
}
}
pub fn default_model(self) -> &'static str {
match self {
ProviderKind::None => "",
ProviderKind::DeepSeek => "deepseek-chat",
ProviderKind::OpenAi => "gpt-4o-mini",
}
}
pub fn requires_key(self) -> bool {
!matches!(self, ProviderKind::None)
}
}
/// A bounded summary of the machine, and nothing else. No home directories, no
/// logs, no credentials, no file contents.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SystemFacts {
pub arch: String,
pub cpu_model: String,
pub cpu_cores: u32,
pub memory_mib: u64,
pub cpu_features: Vec<String>,
pub gpu_vendors: Vec<String>,
pub firmware: String,
pub target_disk: String,
pub disk_size_gib: u64,
pub disk_ssd: bool,
pub gentoo_profile: String,
pub binhost_available: bool,
pub desktop_profile: String,
pub filesystem: String,
pub encryption: String,
pub recommended_kernel_profile: String,
/// Measured compile times (seconds) for the slowest packages, capped.
pub measured_compile_times: BTreeMap<String, u64>,
}
/// Storage facts supplied by the caller (disk probing lives in the executor).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DiskSummary {
pub path: String,
pub size_gib: u64,
pub ssd: bool,
}
const MAX_HISTORY: usize = 40;
impl SystemFacts {
pub fn from_system(
config: &InstallConfig,
hardware: &HardwareReport,
history: &HashMap<String, u64>,
binhost_available: bool,
disk: Option<DiskSummary>,
) -> Self {
let mut measured: Vec<(String, u64)> = history
.iter()
.map(|(atom, secs)| (atom.clone(), *secs))
.collect();
measured.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
measured.truncate(MAX_HISTORY);
let disk = disk.unwrap_or_default();
SystemFacts {
arch: config.system.arch.clone(),
cpu_model: hardware.cpu.model.clone(),
cpu_cores: hardware.cpu.cores,
memory_mib: hardware.memory_mib,
cpu_features: hardware.cpu.features.clone(),
gpu_vendors: hardware
.gpu_vendors()
.into_iter()
.map(|v| v.as_str().to_string())
.collect(),
firmware: hardware.firmware_str().to_string(),
target_disk: disk.path,
disk_size_gib: disk.size_gib,
disk_ssd: disk.ssd,
gentoo_profile: phoebus_core::system::selected_profile(config),
binhost_available,
desktop_profile: config.desktop.profile.to_string(),
filesystem: config.storage.filesystem.to_string(),
encryption: config.encryption.mode.to_string(),
recommended_kernel_profile: hardware.recommended_kernel_profile().to_string(),
measured_compile_times: measured.into_iter().collect(),
}
}
pub fn render(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
}
/// Refuse to send facts if any string field looks like a personal path.
pub fn validate_no_forbidden(&self) -> Result<(), AiError> {
let strings = [
&self.arch,
&self.cpu_model,
&self.firmware,
&self.target_disk,
&self.gentoo_profile,
&self.desktop_profile,
&self.filesystem,
&self.encryption,
&self.recommended_kernel_profile,
];
for value in strings.into_iter().chain(self.gpu_vendors.iter()) {
if is_forbidden_path(value) {
return Err(AiError::PrivateData(value.clone()));
}
}
for atom in self.measured_compile_times.keys() {
if is_forbidden_path(atom) {
return Err(AiError::PrivateData(atom.clone()));
}
}
Ok(())
}
}
/// The instructions given to the model. They are deliberately explicit about
/// the closed action set and the evidence requirement.
pub const SYSTEM_PROMPT: &str = "\
You are the Phoebus OS installation advisor. You may ONLY propose changes using \
this closed set of actions, each with a non-empty reason and optional evidence:
set_hostname, set_timezone, set_locale, set_keymap, set_username, set_target_disk,
set_filesystem (btrfs|ext4), set_encryption (none|luks2), set_kernel_profile
(safe|optimized|aggressive), set_package_policy (balanced|source_first|binary_first),
set_desktop_profile (none|minimal|dwl|full), set_flatpak (bool),
set_binary_packages (bool), set_build_jobs (1-256), set_package_use (atom, flag,
enabled).
Reply with ONLY a JSON object of the form:
{\"version\":1,\"changes\":[{\"action\":\"...\",...}],\"rationale\":[{\"action\":\"...\",\"reason\":\"...\",\"evidence\":[\"...\"]}]}
Rules: prefer stability and a proven boot over speculative performance; never
propose disabling signature verification, enabling ~amd64 globally, weakening
LUKS2/Btrfs/systemd/UEFI, or any shell/command action; do not invent package
atoms; keep required boot/encryption/filesystem settings fixed. You do not have
a shell and cannot execute anything.";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChatMessage {
pub role: String,
pub content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ResponseFormat {
#[serde(rename = "type")]
pub kind: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ChatRequest {
pub model: String,
pub messages: Vec<ChatMessage>,
pub temperature: f32,
#[serde(skip_serializing_if = "Option::is_none")]
pub response_format: Option<ResponseFormat>,
}
/// Build the chat request for a provider. The API key is not part of it.
pub fn build_request(provider: ProviderKind, model: &str, facts: &SystemFacts) -> ChatRequest {
let model = if model.trim().is_empty() {
provider.default_model().to_string()
} else {
model.trim().to_string()
};
let user = format!(
"Detected system facts (JSON):\n{}\n\nPropose a version 1 AiProposal.",
facts.render()
);
ChatRequest {
model,
messages: vec![
ChatMessage {
role: "system".into(),
content: SYSTEM_PROMPT.into(),
},
ChatMessage {
role: "user".into(),
content: user,
},
],
temperature: 0.0,
response_format: Some(ResponseFormat {
kind: "json_object".into(),
}),
}
}
#[derive(Debug, Deserialize)]
struct ChatResponse {
choices: Vec<Choice>,
}
#[derive(Debug, Deserialize)]
struct Choice {
message: ChoiceMessage,
}
#[derive(Debug, Deserialize)]
struct ChoiceMessage {
content: String,
}
/// Extract the assistant's text content from a chat-completions response and
/// strip a Markdown code fence if the model added one.
pub fn extract_content(body: &str) -> Result<String, AiError> {
let parsed: ChatResponse = serde_json::from_str(body)
.map_err(|e| AiError::Provider(format!("invalid chat response: {e}")))?;
let content = parsed
.choices
.first()
.map(|c| c.message.content.trim().to_string())
.filter(|c| !c.is_empty())
.ok_or_else(|| AiError::Provider("model returned no content".into()))?;
let inner = if let Some(rest) = content.strip_prefix("```") {
let rest = rest.strip_prefix("json").unwrap_or(rest);
rest.trim_start_matches(['\n', '\r'])
.trim_end()
.strip_suffix("```")
.unwrap_or(rest)
.trim()
.to_string()
} else {
content
};
if inner.is_empty() {
return Err(AiError::Provider("model returned empty content".into()));
}
Ok(inner)
}
/// Transport used to reach a provider. The executor implements this with curl;
/// tests implement it with canned responses.
pub trait ModelTransport {
fn send(&self, provider: ProviderKind, url: &str, body: &str) -> Result<String, AiError>;
}
/// A transport that always returns a fixed response (tests, offline dry runs).
pub struct TestTransport {
pub response: String,
}
impl TestTransport {
pub fn new(response: impl Into<String>) -> Self {
Self {
response: response.into(),
}
}
/// Wrap a bare proposal JSON in an OpenAI-style chat response.
pub fn proposal(proposal_json: &str) -> Self {
Self::new(
serde_json::json!({
"choices": [{ "message": { "content": proposal_json } }]
})
.to_string(),
)
}
}
impl ModelTransport for TestTransport {
fn send(&self, _provider: ProviderKind, _url: &str, _body: &str) -> Result<String, AiError> {
Ok(self.response.clone())
}
}
/// Ask a provider for a proposal and parse it, fail-closed at every step.
pub fn complete_proposal(
provider: ProviderKind,
model: &str,
facts: &SystemFacts,
transport: &dyn ModelTransport,
) -> Result<AiProposal, AiError> {
if provider == ProviderKind::None {
return Err(AiError::ProviderUnavailable(
"no AI provider selected".into(),
));
}
facts.validate_no_forbidden()?;
let request = build_request(provider, model, facts);
let body = serde_json::to_string(&request)?;
let response = transport.send(provider, provider.endpoint(), &body)?;
let content = extract_content(&response)?;
parse_proposal(&content)
}
#[cfg(test)]
mod tests {
use super::*;
use phoebus_core::config::InstallConfig;
use phoebus_core::hardware::{CpuInfo, GpuInfo, GpuVendor, HardwareReport};
fn facts() -> SystemFacts {
let mut config = InstallConfig::default();
config.desktop.profile = phoebus_core::DesktopProfile::Dwl;
let hardware = HardwareReport {
cpu: CpuInfo {
model: "Test CPU".into(),
cores: 8,
features: vec!["vmx".into(), "avx2".into()],
..Default::default()
},
memory_mib: 16384,
gpus: vec![GpuInfo {
vendor: GpuVendor::Intel,
description: "iGPU".into(),
}],
..Default::default()
};
let history = HashMap::from([("sys-apps/systemd".to_string(), 420u64)]);
SystemFacts::from_system(
&config,
&hardware,
&history,
true,
Some(DiskSummary {
path: "/dev/vda".into(),
size_gib: 32,
ssd: true,
}),
)
}
#[test]
fn facts_contain_only_system_data() {
let facts = facts();
let rendered = facts.render();
assert!(rendered.contains("Test CPU"));
assert!(rendered.contains("/dev/vda"));
assert!(!rendered.contains("/home/"));
assert!(!is_forbidden_path(&facts.target_disk));
facts.validate_no_forbidden().unwrap();
}
#[test]
fn forbidden_paths_in_facts_are_refused() {
let mut facts = facts();
facts.cpu_model = "/home/alice/secret".into();
assert!(matches!(
facts.validate_no_forbidden(),
Err(AiError::PrivateData(_))
));
}
#[test]
fn history_is_capped_and_sorted() {
let mut history = HashMap::new();
for i in 0..100u64 {
history.insert(format!("cat/pkg{i}"), i);
}
let facts = SystemFacts::from_system(
&InstallConfig::default(),
&HardwareReport::default(),
&history,
true,
None,
);
assert_eq!(facts.measured_compile_times.len(), MAX_HISTORY);
// The 40 slowest packages (60..=99) are kept.
assert!(facts
.measured_compile_times
.values()
.all(|v| *v >= 100 - MAX_HISTORY as u64));
}
#[test]
fn provider_endpoints_and_parsing() {
assert_eq!(ProviderKind::parse("ChatGPT"), Some(ProviderKind::OpenAi));
assert_eq!(
ProviderKind::parse("deepseek"),
Some(ProviderKind::DeepSeek)
);
assert_eq!(ProviderKind::parse("continue without AI"), None);
assert_eq!(ProviderKind::parse("none"), Some(ProviderKind::None));
assert!(ProviderKind::OpenAi.endpoint().starts_with("https://"));
assert!(ProviderKind::None.endpoint().is_empty());
assert!(ProviderKind::DeepSeek.requires_key());
assert!(!ProviderKind::None.requires_key());
}
#[test]
fn request_has_no_secret_and_pins_the_schema() {
let request = build_request(ProviderKind::DeepSeek, "", &facts());
let body = serde_json::to_string(&request).unwrap();
assert_eq!(request.model, "deepseek-chat");
assert!(body.contains(SYSTEM_PROMPT.split('.').next().unwrap()));
assert!(!body.to_lowercase().contains("api_key"));
assert!(!body.contains("Bearer"));
assert_eq!(
request.response_format.as_ref().map(|r| r.kind.as_str()),
Some("json_object")
);
}
#[test]
fn extract_content_strips_code_fences() {
let body = r#"{"choices":[{"message":{"content":"```json\n{\"version\":1,\"changes\":[]}\n```"}}]}"#;
let content = extract_content(body).unwrap();
assert_eq!(content, r#"{"version":1,"changes":[]}"#);
assert!(extract_content("not json").is_err());
assert!(extract_content(r#"{"choices":[]}"#).is_err());
}
#[test]
fn test_transport_round_trips_a_proposal() {
let proposal = r#"{"version":1,"changes":[{"action":"set_flatpak","value":true}]}"#;
let transport = TestTransport::proposal(proposal);
let parsed = complete_proposal(ProviderKind::OpenAi, "", &facts(), &transport).unwrap();
assert_eq!(parsed.changes.len(), 1);
}
#[test]
fn unavailable_provider_is_explicit() {
let transport = TestTransport::new("{}");
let err = complete_proposal(ProviderKind::None, "", &facts(), &transport).unwrap_err();
assert!(matches!(err, AiError::ProviderUnavailable(_)));
}
}

View file

@ -282,12 +282,33 @@ impl KernelConfig {
}
}
/// A scoped `package.use` entry: one atom and one flag. Used by the installer
/// defaults and by validated AI proposals.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct PackageUse {
pub atom: String,
pub flag: String,
#[serde(default = "default_enabled")]
pub enabled: bool,
}
fn default_enabled() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct PackagesConfig {
pub policy: PackagePolicy,
pub binary_packages: bool,
pub accept_license: String,
/// Explicit `MAKEOPTS -j` value; `None` derives it from cores and memory.
#[serde(default)]
pub build_jobs: Option<u32>,
/// Extra scoped USE entries appended to `package.use`.
#[serde(default)]
pub package_use: Vec<PackageUse>,
}
impl Default for PackagesConfig {
@ -296,6 +317,8 @@ impl Default for PackagesConfig {
policy: PackagePolicy::Balanced,
binary_packages: true,
accept_license: "@FREE @BINARY-REDISTRIBUTABLE".into(),
build_jobs: None,
package_use: Vec::new(),
}
}
}
@ -473,6 +496,13 @@ impl InstallConfig {
"PACKAGE_POLICY" => self.packages.policy = PackagePolicy::from_str(value)?,
"FEATURES_BINPKG" => self.packages.binary_packages = parse_bool(value),
"ACCEPT_LICENSE" => self.packages.accept_license = value.into(),
"BUILD_JOBS" => {
self.packages.build_jobs = if value.trim().is_empty() {
None
} else {
Some(parse_num(key, value)?)
}
}
"DESKTOP_PROFILE" => self.desktop.profile = DesktopProfile::from_str(value)?,
"FLATPAK" => self.desktop.flatpak = parse_bool(value),

View file

@ -37,11 +37,19 @@ pub struct SnapshotHistory {
}
impl SnapshotHistory {
/// Load the transaction history.
///
/// A missing or zero-length file is treated as empty. Any other read or
/// parse failure is returned, never silently discarded: hidden history
/// would let a caller believe no recovery point exists when one does.
pub fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
let text = std::fs::read_to_string(path).map_err(|e| CoreError::io(path, e))?;
if text.trim().is_empty() {
return Ok(Self::default());
}
let history: SnapshotHistory = toml::from_str(&text)?;
Ok(history)
}
@ -136,4 +144,21 @@ mod tests {
let history = SnapshotHistory::load(&dir.path().join("nope.toml")).unwrap();
assert!(history.records.is_empty());
}
#[test]
fn empty_history_file_is_empty() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("empty.toml");
std::fs::write(&path, " \n").unwrap();
let history = SnapshotHistory::load(&path).unwrap();
assert!(history.records.is_empty());
}
#[test]
fn corrupt_history_is_reported_not_hidden() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("corrupt.toml");
std::fs::write(&path, "this is not = = toml [[[").unwrap();
assert!(SnapshotHistory::load(&path).is_err());
}
}

View file

@ -126,10 +126,15 @@ pub fn selected_profile(config: &InstallConfig) -> String {
// Portage configuration
// ---------------------------------------------------------------------------
pub fn makeopts(cores: u32, memory_mib: u64) -> String {
pub fn makeopts(cores: u32, memory_mib: u64, build_jobs: Option<u32>) -> String {
let cores = if cores == 0 { 4 } else { cores };
let mem_jobs = std::cmp::max(1, memory_mib / 2048);
let jobs = std::cmp::max(1, std::cmp::min(cores + 1, mem_jobs as u32));
let mem_jobs = std::cmp::max(1, memory_mib / 2048) as u32;
let derived = std::cmp::max(1, std::cmp::min(cores + 1, mem_jobs));
// An explicit request is still capped by available memory so a proposal
// cannot make the build exhaust RAM.
let jobs = build_jobs
.map(|j| std::cmp::max(1, std::cmp::min(j, mem_jobs)))
.unwrap_or(derived);
format!("-j{jobs} -l{cores}")
}
@ -166,7 +171,11 @@ pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
o.push_str("FFLAGS=\"${COMMON_FLAGS}\"\n\n");
o.push_str(&format!(
"MAKEOPTS=\"{}\"\n",
makeopts(hardware.cpu.cores, hardware.memory_mib)
makeopts(
hardware.cpu.cores,
hardware.memory_mib,
config.packages.build_jobs
)
));
o.push_str("EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n");
o.push_str("ACCEPT_KEYWORDS=\"amd64\"\n");
@ -195,11 +204,43 @@ pub fn repos_conf() -> String {
o
}
pub const BINHOST_OPENRC: &str =
"https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64";
pub const BINHOST_HARDENED: &str =
"https://distfiles.gentoo.org/releases/amd64/binpackages/23.0/x86-64_hardened";
/// The official signed binhost matching a profile family.
///
/// Gentoo publishes binary packages for the OpenRC and hardened profiles. There
/// is no official systemd binhost, so a systemd system reuses binaries only for
/// packages whose USE matches the OpenRC/hardened build; systemd, polkit,
/// NetworkManager, dbus and util-linux still compile from source. Enabling
/// `systemd` in the global USE therefore does not force needless rebuilds of
/// packages that lack the flag, and this stays a scoped (non-`~amd64`) change.
pub fn binhost_for_profile(profile: &str) -> &'static str {
if profile.contains("hardened") {
BINHOST_HARDENED
} else {
BINHOST_OPENRC
}
}
/// The binhost URI actually used: an explicit configuration value, otherwise
/// the official host for the selected profile.
pub fn resolved_binhost_uri(config: &InstallConfig) -> String {
let configured = config.stage3.binhost_uri.trim();
if configured.is_empty() {
binhost_for_profile(&selected_profile(config)).to_string()
} else {
configured.to_string()
}
}
pub fn binrepos_conf(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str("[gentoo]\n");
o.push_str("priority = 1\n");
o.push_str(&format!("sync-uri = {}\n", config.stage3.binhost_uri));
o.push_str(&format!("sync-uri = {}\n", resolved_binhost_uri(config)));
o.push_str("location = /var/cache/binhost/gentoo\n");
o.push_str("verify-signature = true\n");
o
@ -216,8 +257,11 @@ pub fn package_use(config: &InstallConfig) -> String {
o.push_str("# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n");
o.push_str("sys-apps/systemd boot policykit cryptsetup\n");
o.push_str("# Distribution kernel + systemd-boot generation.\n");
o.push_str("# installkernel REQUIRED_USE: systemd-boot? ( systemd ), ukify? ( uki )\n");
o.push_str("sys-kernel/installkernel dracut systemd systemd-boot uki\n");
o.push_str("# installkernel REQUIRED_USE: systemd-boot? ( systemd );\n");
o.push_str("# the `uki` flag is NOT set: this system uses the BLS layout with\n");
o.push_str("# uki_generator=none, so ukify is never invoked and its extra\n");
o.push_str("# dependencies (and binary-package mismatch) are avoided.\n");
o.push_str("sys-kernel/installkernel dracut systemd systemd-boot\n");
o.push_str("sys-apps/dbus systemd\n");
o.push_str("sys-auth/polkit systemd\n");
o.push_str("sys-apps/util-linux systemd\n");
@ -227,9 +271,17 @@ pub fn package_use(config: &InstallConfig) -> String {
o.push_str("sys-fs/cryptsetup -man\n");
o.push_str("# Networking\n");
o.push_str("net-misc/networkmanager systemd\n");
// Audio (PipeWire + WirePlumber are the standard stack). Emit pipewire
// once; the previous duplicate entry is gone. `systemd` is added only for
// the desktop profile that installs PipeWire.
o.push_str("# Audio (PipeWire + WirePlumber are the standard stack)\n");
o.push_str("media-video/pipewire sound-server\n");
o.push_str("media-video/wireplumber\n");
let pipewire = if config.desktop.profile == DesktopProfile::None {
"media-video/pipewire sound-server".to_string()
} else {
"media-video/pipewire sound-server systemd".to_string()
};
o.push_str(&pipewire);
o.push('\n');
if config.desktop.profile != DesktopProfile::None {
o.push_str("# Desktop (Wayland-first, XWayland compatibility)\n");
o.push_str("x11-libs/cairo X\n");
@ -237,7 +289,14 @@ pub fn package_use(config: &InstallConfig) -> String {
o.push_str("gui-libs/gtk wayland\n");
o.push_str("media-libs/libglvnd X\n");
o.push_str("x11-terms/kitty wayland\n");
o.push_str("media-video/pipewire systemd\n");
}
// Scoped use entries from validated configuration/AI proposals.
if !config.packages.package_use.is_empty() {
o.push_str("# Accepted scoped USE changes\n");
for entry in &config.packages.package_use {
let prefix = if entry.enabled { "" } else { "-" };
o.push_str(&format!("{} {}{}\n", entry.atom, prefix, entry.flag));
}
}
o
}
@ -329,6 +388,116 @@ pub fn kernel_profile_config(config: &InstallConfig) -> String {
o
}
/// The Wayland session entry point written to `/usr/local/bin/phoebus-session`.
///
/// Reliability properties (covered by tests):
/// * the session bus is established before any client starts;
/// * `xdg_runtime_dir` is derived when logind did not provide it;
/// * `dwl` starts first and the helper clients wait for the Wayland socket,
/// so they never race the compositor;
/// * the polkit authentication agent is started;
/// * helpers are killed when `dwl` exits, so logout leaves nothing behind.
pub const PHOEBUS_SESSION_SCRIPT: &str = r#"#!/bin/bash
# Phoebus Wayland session (generated by the installer).
#
# Start with: phoebus-session
#
# Hotkeys (dwl defaults):
# Mod+Shift+Return terminal Mod+d launcher
# Mod+Shift+q close window Mod+j / Mod+k focus next/prev
# Mod+1..9 workspace Mod+Shift+e quit dwl
set -u
# loginctl normally provides XDG_RUNTIME_DIR. Fall back to the conventional
# per-user path so a manual VT start still works.
if [ -z "${XDG_RUNTIME_DIR:-}" ]; then
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
if [ ! -d "$XDG_RUNTIME_DIR" ]; then
echo "phoebus-session: XDG_RUNTIME_DIR $XDG_RUNTIME_DIR is missing" >&2
exit 1
fi
export XDG_SESSION_TYPE=wayland
export XDG_CURRENT_DESKTOP=phoebus
export XDG_SESSION_DESKTOP=phoebus
export MOZ_ENABLE_WAYLAND=1
export QT_QPA_PLATFORM=wayland
export GDK_BACKEND=wayland,x11
export _JAVA_AWT_WM_NONREPARENTING=1
# Every client must share one session bus. Re-exec once under a fresh bus when
# nothing has provided one (e.g. started directly from a VT).
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
exec dbus-run-session -- "$0" "$@"
fi
# Use software rendering when there is no render node (e.g. a VM).
if [ -z "${WLR_RENDERER:-}" ] && [ ! -e /dev/dri/renderD128 ]; then
export WLR_RENDERER=pixman
export WLR_RENDERER_ALLOW_SOFTWARE=1
fi
socket="${XDG_RUNTIME_DIR}/${WAYLAND_DISPLAY:-wayland-0}"
HELPERS=""
start_helper() {
"$@" >/dev/null 2>&1 &
HELPERS="$HELPERS $!"
}
cleanup() {
trap - EXIT INT TERM
for pid in $HELPERS; do
kill "$pid" 2>/dev/null || true
done
}
trap cleanup EXIT INT TERM
# dwl creates the Wayland socket. Start it first, then wait for the socket so
# helpers do not race the compositor (they used to connect before wayland-0
# existed and exit immediately).
dwl &
DWL_PID=$!
waited=0
while [ ! -S "$socket" ]; do
if ! kill -0 "$DWL_PID" 2>/dev/null; then
echo "phoebus-session: dwl exited before creating $socket" >&2
exit 1
fi
if [ "$waited" -ge 100 ]; then
echo "phoebus-session: timed out waiting for $socket" >&2
kill "$DWL_PID" 2>/dev/null || true
exit 1
fi
sleep 0.1
waited=$((waited + 1))
done
start_helper waybar
start_helper mako
if [ -n "${PHOEBUS_WALLPAPER:-}" ] && [ -f "$PHOEBUS_WALLPAPER" ]; then
start_helper swaybg -i "$PHOEBUS_WALLPAPER"
else
start_helper swaybg -c '#1e1e2e'
fi
# polkit authentication agent: required for graphical privilege prompts.
POLKIT_AGENT="$(command -v polkit-gnome-authentication-agent-1 2>/dev/null \
|| echo /usr/libexec/polkit-gnome-authentication-agent-1)"
if [ -x "$POLKIT_AGENT" ]; then
start_helper "$POLKIT_AGENT"
else
echo "phoebus-session: polkit agent not found; graphical authentication may fail" >&2
fi
# Run until the compositor exits, then the EXIT trap stops the helpers.
wait "$DWL_PID"
"#;
/// Btrfs mount options, matching the proven behavior.
pub fn btrfs_mount_opts(compress: &str, ssd: bool) -> String {
let mut opts = format!("noatime,compress={compress},space_cache=v2");
@ -508,6 +677,61 @@ mod tests {
assert!(text.contains("--backtrack=100"));
}
#[test]
fn makeopts_caps_explicit_jobs_by_memory() {
assert_eq!(makeopts(8, 8192, None), "-j4 -l8");
assert_eq!(makeopts(8, 8192, Some(2)), "-j2 -l8");
assert_eq!(makeopts(8, 8192, Some(99)), "-j4 -l8");
assert_eq!(makeopts(0, 0, None), "-j1 -l4");
}
#[test]
fn package_use_is_clean_and_keeps_required_flags() {
let mut cfg = InstallConfig::default();
cfg.desktop.profile = DesktopProfile::Dwl;
let text = package_use(&cfg);
// Required boot/encryption/session flags stay.
assert!(text.contains("sys-apps/systemd boot policykit cryptsetup"));
assert!(text.contains("sys-kernel/installkernel dracut systemd systemd-boot"));
// BLS does not need the `uki` flag, and the empty wireplumber line and
// the duplicate pipewire line are gone.
assert!(!text.contains(" systemd-boot uki"));
assert!(!text.contains("media-video/wireplumber\n"));
assert_eq!(text.matches("media-video/pipewire").count(), 1);
assert!(text.contains("media-video/pipewire sound-server systemd"));
}
#[test]
fn package_use_appends_validated_entries() {
let mut cfg = InstallConfig::default();
cfg.packages.package_use.push(crate::config::PackageUse {
atom: "www-client/firefox".into(),
flag: "wayland".into(),
enabled: false,
});
let text = package_use(&cfg);
assert!(text.contains("www-client/firefox -wayland"));
}
#[test]
fn binhost_selection_follows_profile() {
assert_eq!(binhost_for_profile(PROFILE_SYSTEMD_MINIMAL), BINHOST_OPENRC);
assert_eq!(
binhost_for_profile("default/linux/amd64/23.0/hardened/systemd"),
BINHOST_HARDENED
);
let mut cfg = InstallConfig::default();
cfg.stage3.binhost_uri.clear();
cfg.stage3.gentoo_profile = "default/linux/amd64/23.0/hardened/systemd".into();
assert_eq!(resolved_binhost_uri(&cfg), BINHOST_HARDENED);
cfg.stage3.binhost_uri = "https://example.invalid/binpkgs".into();
assert_eq!(
resolved_binhost_uri(&cfg),
"https://example.invalid/binpkgs"
);
assert!(binrepos_conf(&cfg).contains("verify-signature = true"));
}
#[test]
fn desktop_selects_desktop_systemd_profile() {
let mut cfg = InstallConfig::default();
@ -533,6 +757,29 @@ mod tests {
assert_eq!(count, 1);
}
#[test]
fn session_script_is_race_free_and_cleans_up() {
let script = PHOEBUS_SESSION_SCRIPT;
// The compositor starts before the clients and the clients wait for
// the socket it creates.
let dwl = script.find("dwl &").expect("starts dwl in the background");
let socket_wait = script
.find("while [ ! -S \"$socket\" ]")
.expect("waits for the wayland socket");
let waybar = script.find("start_helper waybar").expect("starts waybar");
assert!(dwl < socket_wait && socket_wait < waybar);
// A session bus and runtime dir are established.
assert!(script.contains("dbus-run-session"));
assert!(script.contains("XDG_RUNTIME_DIR"));
// The polkit agent is started when present.
assert!(script.contains("POLKIT_AGENT"));
// Helpers are reaped when the compositor exits.
assert!(script.contains("cleanup()"));
assert!(script.contains("trap cleanup EXIT INT TERM"));
assert!(script.contains("wait \"$DWL_PID\""));
assert!(!script.contains("exec dwl"));
}
#[test]
fn encrypted_cmdline_requires_uuid() {
let cfg = InstallConfig::default();

View file

@ -139,6 +139,38 @@ pub fn password_strength(password: &str) -> &'static str {
}
}
/// Validate a package atom: `category/name`, with only safe characters.
pub fn validate_package_atom(atom: &str) -> Result<(), String> {
if atom.split('/').count() != 2 || atom.is_empty() {
return Err(format!("package atom must be category/name: {atom}"));
}
if !atom
.chars()
.all(|c| c.is_ascii_alphanumeric() || "/*._+-".contains(c))
{
return Err(format!("invalid package atom: {atom}"));
}
Ok(())
}
/// Validate a USE flag. A leading `-` disables the flag; wildcards are refused
/// so a proposal cannot change flags across every package.
pub fn validate_use_flag(flag: &str) -> Result<(), String> {
if flag.contains('*') {
return Err("wildcard USE flags are not allowed".into());
}
let name = flag.strip_prefix('-').unwrap_or(flag);
if name.is_empty()
|| name.len() > 64
|| !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '+' || c == '@')
{
return Err(format!("invalid USE flag: {flag}"));
}
Ok(())
}
/// Validate the whole configuration. Disk protection is checked separately
/// against probed hardware at preflight time.
pub fn validate_config(config: &InstallConfig) -> Vec<ValidationIssue> {
@ -200,6 +232,22 @@ pub fn validate_config(config: &InstallConfig) -> Vec<ValidationIssue> {
"ACCEPT_LICENSE must not be empty",
));
}
if let Some(jobs) = config.packages.build_jobs {
if jobs == 0 || jobs > 256 {
issues.push(ValidationIssue::new(
"build_jobs",
"build jobs must be between 1 and 256",
));
}
}
for entry in &config.packages.package_use {
if let Err(e) = validate_package_atom(&entry.atom) {
issues.push(ValidationIssue::new("package_use", e));
}
if let Err(e) = validate_use_flag(&entry.flag) {
issues.push(ValidationIssue::new("package_use", e));
}
}
issues
}
@ -243,6 +291,29 @@ mod tests {
assert!(fields.contains(&"target_disk"));
}
#[test]
fn package_use_and_jobs_are_validated() {
assert!(validate_package_atom("www-client/firefox").is_ok());
assert!(validate_package_atom("firefox").is_err());
assert!(validate_package_atom("sys-fs/btrfs-progs").is_ok());
assert!(validate_use_flag("-man").is_ok());
assert!(validate_use_flag("systemd").is_ok());
assert!(validate_use_flag("*").is_err());
assert!(validate_use_flag("").is_err());
assert!(validate_use_flag("bad flag").is_err());
let mut cfg = InstallConfig::default();
cfg.packages.build_jobs = Some(0);
cfg.packages.package_use.push(crate::config::PackageUse {
atom: "notanatatom".into(),
flag: "*.x".into(),
enabled: true,
});
let fields: Vec<&str> = validate_config(&cfg).iter().map(|i| i.field).collect();
assert!(fields.contains(&"build_jobs"));
assert!(fields.contains(&"package_use"));
}
#[test]
fn complete_config_passes() {
let mut cfg = InstallConfig::default();

View file

@ -41,6 +41,23 @@ pub fn execute(
if action.is_mutating() && auth.is_none() {
return Err(ExecError::NotAuthorized(action.describe()));
}
// A protective snapshot must exist before a high-risk change. If the
// snapshots subvolume is present but the snapshot cannot be created, fail
// closed rather than proceed without a recovery point. A system without a
// `.snapshots` subvolume (e.g. a non-Btrfs root) is a warning, not a block.
if action.risk() == phoebus_core::action::Risk::High && !exec.dry_run {
if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
snapshot::create_and_record(exec, auth, root, "/", &action.describe())?;
} else {
exec.logger.warn(format!(
"no {}/ subvolume; proceeding without a protective snapshot",
snapshot::SNAPSHOT_DIR
));
}
}
let mut snapshot_id = None;
let output = match action {
SystemAction::InspectService { name } => {
@ -107,7 +124,7 @@ pub fn execute(
)
}
SystemAction::History => {
let history = snapshot::read_history(root);
let history = snapshot::read_history(root)?;
if history.records.is_empty() {
"no transaction history".to_string()
} else {
@ -160,6 +177,64 @@ mod tests {
execute(&exec, &action, None, Path::new("/")).unwrap();
}
#[test]
fn high_risk_action_snapshots_before_running() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
execute(
&exec,
&SystemAction::UpdateSystem,
Some(&auth),
Path::new(&exec.root),
)
.unwrap();
let programs = runner.programs();
let btrfs = programs
.iter()
.position(|p| p == "btrfs")
.expect("snapshot");
let emerge = programs.iter().position(|p| p == "emerge").expect("emerge");
assert!(
btrfs < emerge,
"protective snapshot must precede the mutation: {programs:?}"
);
}
#[test]
fn high_risk_action_aborts_when_protective_snapshot_fails() {
let runner = RecordingRunner::new();
runner.fail("btrfs", "snapshot failed");
let exec = make_exec(runner.clone());
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let err = execute(
&exec,
&SystemAction::UpdateSystem,
Some(&auth),
Path::new(&exec.root),
)
.unwrap_err();
assert!(matches!(err, ExecError::Command { .. }), "got {err}");
// The mutation must not run, and no snapshot may be recorded as
// committed when creation failed.
assert!(!runner.programs().iter().any(|p| p == "emerge"));
let history = snapshot::read_history(Path::new(&exec.root)).unwrap();
assert!(history.records.is_empty());
}
#[test]
fn history_query_reports_corrupt_file() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let path = crate::snapshot::history_path(Path::new(&exec.root));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "not = = toml [[[").unwrap();
let err = execute(&exec, &SystemAction::History, None, Path::new(&exec.root)).unwrap_err();
assert!(matches!(err, ExecError::Core(_)), "got {err}");
}
#[test]
fn enable_builds_separate_arguments() {
let runner = RecordingRunner::new();

View file

@ -0,0 +1,158 @@
//! Model provider transport.
//!
//! The API key never appears on a command line or in a log. It is injected into
//! a curl configuration file passed on stdin, while curl reads the JSON request
//! body from a 0600 temporary file. The body contains only the approved facts
//! built by `phoebus_ai::provider`.
use std::path::Path;
use phoebus_ai::provider::{ModelTransport, ProviderKind};
use phoebus_ai::AiError;
use phoebus_core::SecretString;
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// Read an API key from a file that must be mode 0600. The value is returned
/// as a `SecretString`; callers must register it with the redactor (the
/// transport does this automatically).
pub fn load_api_key(path: &Path) -> Result<SecretString> {
use std::os::unix::fs::PermissionsExt;
let meta = std::fs::metadata(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
if meta.permissions().mode() & 0o077 != 0 {
return Err(ExecError::operation(
"ai",
"read API key",
format!("{} must be mode 0600", path.display()),
));
}
let key = std::fs::read_to_string(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
let key = key.trim().to_string();
if key.is_empty() {
return Err(ExecError::operation(
"ai",
"read API key",
"API key file is empty",
));
}
Ok(SecretString::new(key))
}
/// A transport that talks to an OpenAI-compatible endpoint with curl.
pub struct CurlTransport<'a> {
exec: &'a Exec,
api_key: SecretString,
}
impl<'a> CurlTransport<'a> {
pub fn new(exec: &'a Exec, api_key: SecretString) -> Self {
exec.register_secret(&api_key);
Self { exec, api_key }
}
}
impl ModelTransport for CurlTransport<'_> {
fn send(
&self,
_provider: ProviderKind,
url: &str,
body: &str,
) -> std::result::Result<String, AiError> {
let mut request = tempfile::Builder::new()
.prefix("phoebus-ai-request.")
.tempfile()
.map_err(|e| AiError::Provider(e.to_string()))?;
use std::io::Write;
request
.write_all(body.as_bytes())
.and_then(|_| request.flush())
.map_err(|e| AiError::Provider(e.to_string()))?;
// curl reads this config from stdin, so Exec marks the stdin as hidden
// and never logs it. The key is therefore absent from argv and logs.
let config = format!(
"url = \"{url}\"\n\
header = \"Content-Type: application/json\"\n\
header = \"Authorization: Bearer {key}\"\n\
data = \"@{path}\"\n\
silent\nshow-error\nfail-with-body\nmax-time = 120\n",
key = self.api_key.expose(),
path = request.path().display()
);
let spec = CommandSpec::new("ai", "query model", "curl")
.args(["-sS", "-K", "-"])
.stdin(config.into_bytes());
let out = self
.exec
.run(spec)
.map_err(|e| AiError::Provider(e.to_string()))?;
Ok(out.stdout_lossy())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::{CommandOutput, RecordingRunner};
use crate::log::Logger;
use phoebus_core::Redactor;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn api_key_must_be_mode_0600() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("key");
std::fs::write(&path, "sk-test\n").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(load_api_key(&path).is_err());
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
assert_eq!(load_api_key(&path).unwrap().expose(), "sk-test");
}
#[test]
fn curl_transport_keeps_the_key_out_of_arguments_and_logs() {
let runner = RecordingRunner::new();
runner.set_response(
"curl",
CommandOutput {
status: 0,
success: true,
stdout: br#"{"choices":[{"message":{"content":"{}"}}]}"#.to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
},
);
let exec = make_exec(runner.clone());
let transport = CurlTransport::new(&exec, SecretString::new("sk-secret-value"));
let out = transport
.send(
ProviderKind::OpenAi,
"https://example.invalid/v1/chat/completions",
r#"{"model":"m"}"#,
)
.unwrap();
assert!(out.contains("choices"));
let specs = runner.recorded();
let spec = &specs[0];
assert_eq!(spec.program, "curl");
assert!(
!spec.args.iter().any(|a| a.contains("sk-secret-value")),
"the key must not be in argv: {:?}",
spec.args
);
let stdin = String::from_utf8(spec.stdin.clone().unwrap()).unwrap();
assert!(stdin.contains("Authorization: Bearer sk-secret-value"));
// And the key is registered for redaction.
assert_eq!(exec.redactor().redact("sk-secret-value"), "<redacted>");
}
}

View file

@ -55,36 +55,7 @@ pub fn write_session_script(exec: &Exec, config: &InstallConfig) -> Result<()> {
return Ok(());
}
let target = exec.target();
let script = r#"#!/bin/bash
# Phoebus Wayland session (generated by the installer).
#
# Start with: phoebus-session
#
# Hotkeys (dwl defaults):
# Mod+Shift+Return terminal Mod+d launcher
# Mod+Shift+q close window Mod+j / Mod+k focus next/prev
# Mod+1..9 workspace Mod+Shift+e quit dwl
export XDG_SESSION_TYPE=wayland
export XDG_CURRENT_DESKTOP=phoebus
export XDG_SESSION_DESKTOP=phoebus
# Use software rendering when there is no render node (e.g. a VM).
if [ -z "${WLR_RENDERER:-}" ] && [ ! -e /dev/dri/renderD128 ]; then
export WLR_RENDERER=pixman
export WLR_RENDERER_ALLOW_SOFTWARE=1
fi
waybar >/dev/null 2>&1 &
mako >/dev/null 2>&1 &
if [ -n "${PHOEBUS_WALLPAPER:-}" ] && [ -f "$PHOEBUS_WALLPAPER" ]; then
swaybg -i "$PHOEBUS_WALLPAPER" >/dev/null 2>&1 &
else
swaybg -c '#1e1e2e' >/dev/null 2>&1 &
fi
exec dwl
"#;
let script = sysgen::PHOEBUS_SESSION_SCRIPT;
let path = target.resolve("usr/local/bin/phoebus-session")?;
target.write("usr/local/bin/phoebus-session", script)?;
use std::os::unix::fs::PermissionsExt;
@ -131,7 +102,7 @@ mod tests {
}
#[test]
fn session_script_is_written_and_execs_dwl() {
fn session_script_waits_for_the_socket_and_starts_polkit() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let mut cfg = InstallConfig::default();
@ -139,9 +110,14 @@ mod tests {
write_session_script(&exec, &cfg).unwrap();
let path = exec.root.join("usr/local/bin/phoebus-session");
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("exec dwl"));
assert!(text.contains("waybar"));
assert!(text.contains("mako"));
// dwl is started first and waited on; helpers wait for the socket.
assert!(text.contains("dwl &"));
assert!(text.contains("wait \"$DWL_PID\""));
assert!(!text.contains("exec dwl"), "exec would skip helper cleanup");
assert!(text.contains("wayland-0"));
assert!(text.contains("polkit-gnome-authentication-agent-1"));
assert!(text.contains("start_helper waybar"));
assert!(text.contains("trap cleanup EXIT INT TERM"));
use std::os::unix::fs::PermissionsExt;
assert_ne!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,

View file

@ -6,6 +6,7 @@
pub mod actions;
pub mod admin;
pub mod ai;
pub mod auth;
pub mod boot;
pub mod command;

View file

@ -29,8 +29,26 @@ pub fn history_path(root: &Path) -> PathBuf {
root.join(HISTORY_REL)
}
pub fn read_history(root: &Path) -> SnapshotHistory {
SnapshotHistory::load(&history_path(root)).unwrap_or_default()
/// Read the transaction history, surfacing a corrupt file instead of hiding it.
///
/// A missing or zero-length file is empty; anything else is an error so a
/// caller never mistakes an unreadable history for "no snapshots".
pub fn read_history(root: &Path) -> Result<SnapshotHistory> {
SnapshotHistory::load(&history_path(root)).map_err(ExecError::Core)
}
/// The transaction history, or a logged warning and the last-known-empty
/// history. Only for read paths that must not fail a `sys` query.
pub fn read_history_lossy(exec: &Exec, root: &Path) -> SnapshotHistory {
match read_history(root) {
Ok(history) => history,
Err(e) => {
exec.logger.warn(format!(
"snapshot history is unreadable: {e}; treating as unavailable"
));
SnapshotHistory::default()
}
}
}
pub fn write_history(root: &Path, history: &SnapshotHistory) -> Result<()> {
@ -86,7 +104,7 @@ pub fn create_and_record(
) -> Result<SnapshotRecord> {
let mut record = create(exec, auth, root, source_subvol, operation)?;
record.status = SnapshotStatus::Committed;
let mut history = read_history(root);
let mut history = read_history(root)?;
history.append(record.clone());
write_history(root, &history)?;
exec.logger
@ -151,8 +169,22 @@ mod tests {
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let record = create_and_record(&exec, &auth, Path::new(&exec.root), "/", "risk").unwrap();
assert_eq!(record.status, SnapshotStatus::Committed);
let history = read_history(Path::new(&exec.root));
let history = read_history(Path::new(&exec.root)).unwrap();
assert_eq!(history.records.len(), 1);
assert_eq!(history.latest().unwrap().id, record.id);
}
#[test]
fn corrupt_history_is_surfaced() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let history_path = history_path(Path::new(&exec.root));
std::fs::create_dir_all(history_path.parent().unwrap()).unwrap();
std::fs::write(&history_path, "not = = toml [[[").unwrap();
assert!(read_history(Path::new(&exec.root)).is_err());
// The lossy variant keeps read paths working but does not pretend the
// history was empty.
let lossy = read_history_lossy(&exec, Path::new(&exec.root));
assert!(lossy.records.is_empty());
}
}

View file

@ -13,6 +13,7 @@ use crate::error::{ExecError, Result};
use crate::exec::Exec;
use crate::portage;
#[derive(Debug)]
pub struct PrepareOutcome {
pub started: bool,
pub note: String,
@ -100,34 +101,56 @@ pub fn prepare(exec: &Exec, root: &Path, cores: u32, force: bool) -> Result<Prep
};
save_state(exec, root, &state)?;
let result = (|| -> Result<()> {
portage::chroot(exec, root, "emerge", &fetch_args())?;
state.note = "building binary packages".into();
// Phase 1: distfiles. A failure here is a real failure.
if let Err(e) = portage::chroot(exec, root, "emerge", &fetch_args()) {
state.status = PrepareStatus::Failed;
state.note = describe_failure(&e);
let _ = save_state(exec, root, &state);
portage::chroot(exec, root, "emerge", &build_args())?;
Ok(())
})();
return Err(e);
}
match result {
// Phase 2: reusable binary packages. `--buildpkgonly` refuses while
// dependencies still need merging, which is the common case for a system
// that is behind on updates. The distfiles are already fetched, so record
// that honestly as Ready with the reason rather than a hard failure that
// would hide the successful fetch. Activation stays explicit.
state.note = "building binary packages".into();
let _ = save_state(exec, root, &state);
match portage::chroot(exec, root, "emerge", &build_args()) {
Ok(()) => {
state.status = PrepareStatus::Ready;
state.note = "updates prepared (not activated)".into();
state.last_prepared_unix = now_unix();
save_state(exec, root, &state)?;
exec.logger
.info("background update preparation complete (not activated)");
Ok(PrepareOutcome {
started: true,
note: state.note.clone(),
})
}
Err(e) => {
state.status = PrepareStatus::Failed;
state.note = format!("{e}");
let _ = save_state(exec, root, &state);
Err(e)
state.status = PrepareStatus::Ready;
state.note = format!(
"distfiles fetched; binary prebuild skipped: {}",
describe_failure(&e)
);
exec.logger.warn(format!("binary prebuild skipped: {e}"));
}
}
state.last_prepared_unix = now_unix();
save_state(exec, root, &state)?;
Ok(PrepareOutcome {
started: true,
note: state.note.clone(),
})
}
/// Include the (already redacted) stderr tail of a failed command so the state
/// explains *why* preparation failed instead of only the exit status.
fn describe_failure(error: &ExecError) -> String {
match error {
ExecError::Command { stderr, .. } if !stderr.trim().is_empty() => {
let lines: Vec<&str> = stderr.lines().collect();
let tail = lines[lines.len().saturating_sub(5)..].join("\n");
format!("{error}: {tail}")
}
_ => format!("{error}"),
}
}
fn now_unix() -> u64 {
@ -172,6 +195,78 @@ mod tests {
assert_eq!(state.status, PrepareStatus::Ready);
}
#[test]
fn failed_prepare_records_stderr_detail() {
let runner = RecordingRunner::new();
runner.fail("chroot", "!!! emerge failed: unsatisfied dependency");
let exec = make_exec(runner);
let root = Path::new(&exec.root);
let err = prepare(&exec, root, 8, true).unwrap_err();
assert!(matches!(err, ExecError::Command { .. }));
let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Failed);
assert!(
state.note.contains("unsatisfied dependency"),
"note was {}",
state.note
);
}
#[test]
fn binary_prebuild_skipped_after_a_successful_fetch_is_ready() {
use crate::command::{CommandOutput, ProcessRunner};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
// First emerge (fetch) succeeds; second (buildpkgonly) fails with the
// real Portage "dependencies must be merged" condition.
struct FetchOkBuildFail {
calls: AtomicUsize,
}
impl ProcessRunner for FetchOkBuildFail {
fn execute(&self, _spec: &crate::command::CommandSpec) -> Result<CommandOutput> {
let n = self.calls.fetch_add(1, Ordering::SeqCst);
if n == 0 {
Ok(CommandOutput {
status: 0,
success: true,
stdout: Vec::new(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
})
} else {
Ok(CommandOutput {
status: 1,
success: false,
stdout: Vec::new(),
stderr: b"!!! --buildpkgonly requires all dependencies to be merged."
.to_vec(),
duration: Duration::from_millis(1),
})
}
}
}
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(FetchOkBuildFail {
calls: AtomicUsize::new(0),
}),
logger,
false,
path.join("root"),
path,
);
let root = Path::new(&exec.root);
let outcome = prepare(&exec, root, 8, true).unwrap();
assert!(outcome.started);
assert!(outcome.note.contains("binary prebuild skipped"));
let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Ready);
assert!(state.note.contains("dependencies to be merged"));
}
#[test]
fn state_roundtrip() {
let runner = RecordingRunner::new();

View file

@ -0,0 +1,155 @@
//! Functional test of the generated `phoebus-session` script.
//!
//! Runs the real script against stub `dwl`/helper binaries so the startup
//! ordering, the Wayland-socket wait, the polkit agent and helper cleanup are
//! exercised without a physical seat or a Wayland compositor.
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use phoebus_core::system::PHOEBUS_SESSION_SCRIPT;
fn write_exec(path: &Path, body: &str) {
std::fs::write(path, body).unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
/// dwl stub: creates a real unix socket at $XDG_RUNTIME_DIR/wayland-0 and exits
/// after a moment so the session ends.
const DWL_OK: &str = r#"#!/bin/sh
echo dwl-started >> "$SESSION_TEST_DIR/dwl.log"
exec python3 -c 'import os,socket,time; s=socket.socket(socket.AF_UNIX); s.bind(os.path.join(os.environ["XDG_RUNTIME_DIR"],"wayland-0")); s.listen(1); time.sleep(3)'
"#;
/// dwl stub that fails before creating the socket.
const DWL_FAIL: &str = "#!/bin/sh\nexit 1\n";
/// Helper stub: records whether the Wayland socket existed when it started,
/// stores its pid, then sleeps so cleanup has something to kill.
const HELPER: &str = r#"#!/bin/sh
name="$(basename "$0")"
if [ -S "$XDG_RUNTIME_DIR/wayland-0" ]; then s=ok; else s=missing; fi
echo "$name $s" >> "$SESSION_TEST_DIR/helpers.log"
echo $$ >> "$SESSION_TEST_DIR/helper-pids"
exec sleep 30
"#;
fn wait_timeout(child: &mut Child, secs: u64) -> std::process::ExitStatus {
let deadline = Instant::now() + Duration::from_secs(secs);
loop {
if let Some(status) = child.try_wait().unwrap() {
return status;
}
if Instant::now() >= deadline {
let _ = child.kill();
panic!("session script did not exit within {secs}s");
}
std::thread::sleep(Duration::from_millis(100));
}
}
struct Fixture {
dir: tempfile::TempDir,
script: std::path::PathBuf,
bin: std::path::PathBuf,
runtime: std::path::PathBuf,
}
impl Fixture {
fn new(dwl_body: &str) -> Self {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("bin");
let runtime = dir.path().join("runtime");
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(&runtime).unwrap();
let script = dir.path().join("phoebus-session");
write_exec(&script, PHOEBUS_SESSION_SCRIPT);
write_exec(&bin.join("dwl"), dwl_body);
for helper in [
"waybar",
"mako",
"swaybg",
"polkit-gnome-authentication-agent-1",
] {
write_exec(&bin.join(helper), HELPER);
}
Self {
dir,
script,
bin,
runtime,
}
}
fn run(&self) -> (std::process::ExitStatus, String) {
let mut child = Command::new("bash")
.arg(&self.script)
.env_clear()
.env("PATH", format!("{}:/usr/bin:/bin", self.bin.display()))
.env("XDG_RUNTIME_DIR", &self.runtime)
// Skip the dbus-run-session re-exec; the session bus is not what
// this test exercises.
.env("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/test-bus")
.env("SESSION_TEST_DIR", self.dir.path())
.env("HOME", self.dir.path())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let status = wait_timeout(&mut child, 20);
let mut stderr = String::new();
use std::io::Read;
if let Some(mut e) = child.stderr.take() {
let _ = e.read_to_string(&mut stderr);
}
(status, stderr)
}
fn read(&self, name: &str) -> String {
std::fs::read_to_string(self.dir.path().join(name)).unwrap_or_default()
}
}
#[test]
fn helpers_wait_for_the_socket_and_are_reaped() {
let fixture = Fixture::new(DWL_OK);
let (status, stderr) = fixture.run();
assert!(status.success(), "session failed: {stderr}");
// Every helper observed the socket: they did not race the compositor.
let log = fixture.read("helpers.log");
for name in [
"waybar",
"mako",
"swaybg",
"polkit-gnome-authentication-agent-1",
] {
assert!(log.contains(&format!("{name} ok")), "helper log: {log:?}");
}
assert!(
!log.contains("missing"),
"a helper raced the socket: {log:?}"
);
// The helpers were killed when dwl exited (logout leaves nothing behind).
let pids = fixture.read("helper-pids");
assert!(!pids.trim().is_empty(), "no helper pids recorded");
std::thread::sleep(Duration::from_millis(300));
for pid in pids.lines() {
assert!(
!Path::new(&format!("/proc/{}", pid.trim())).exists(),
"helper {pid} survived logout"
);
}
}
#[test]
fn failure_to_create_the_socket_is_reported() {
let fixture = Fixture::new(DWL_FAIL);
let (status, stderr) = fixture.run();
assert!(!status.success(), "a dead compositor must fail the session");
assert!(stderr.contains("dwl exited before creating"), "{stderr}");
assert!(fixture.read("helpers.log").is_empty());
}

View file

@ -12,6 +12,7 @@ path = "src/main.rs"
[dependencies]
phoebus-core.workspace = true
phoebus-executor.workspace = true
phoebus-ai.workspace = true
phoebus-tui = { path = "../phoebus-tui" }
clap.workspace = true
serde.workspace = true

View file

@ -0,0 +1,119 @@
//! Guided (AI-assisted) installation.
//!
//! This is the only place a model response becomes configuration. The response
//! is parsed into the closed `AiProposal` schema, reviewed with mandatory
//! evidence and conflict detection, and applied atomically. The model never
//! receives secrets and never reaches the executor.
use std::path::Path;
use phoebus_ai::provider::{complete_proposal, ModelTransport, ProviderKind, SystemFacts};
use phoebus_ai::{parse_proposal, review, AiError, ReviewOutcome};
use phoebus_core::InstallConfig;
/// Review a full chat-completions response body and apply the accepted changes.
pub fn review_response(
config: &mut InstallConfig,
response_body: &str,
) -> Result<ReviewOutcome, AiError> {
let content = phoebus_ai::provider::extract_content(response_body)?;
let proposal = parse_proposal(&content)?;
review(config, &proposal)
}
/// Review a bare proposal (already-extracted JSON) and apply it.
pub fn review_proposal_text(
config: &mut InstallConfig,
text: &str,
) -> Result<ReviewOutcome, AiError> {
let proposal = parse_proposal(text)?;
review(config, &proposal)
}
/// Read a proposal from a file. The file may be a full chat response (as a
/// provider returns) or a bare proposal JSON object. Review is atomic, so a
/// failed first interpretation leaves the configuration untouched.
pub fn review_file(config: &mut InstallConfig, path: &Path) -> Result<ReviewOutcome, AiError> {
let text = std::fs::read_to_string(path)
.map_err(|e| AiError::Provider(format!("cannot read {}: {e}", path.display())))?;
if let Ok(outcome) = review_response(config, &text) {
return Ok(outcome);
}
review_proposal_text(config, &text)
}
/// Ask a provider for a proposal and review it (fail-closed).
pub fn generate_and_review(
config: &mut InstallConfig,
facts: &SystemFacts,
provider: ProviderKind,
model: &str,
transport: &dyn ModelTransport,
) -> Result<ReviewOutcome, AiError> {
let proposal = complete_proposal(provider, model, facts, transport)?;
review(config, &proposal)
}
#[cfg(test)]
mod tests {
use super::*;
use phoebus_ai::provider::TestTransport;
const PROPOSAL: &str = r#"{
"version": 1,
"changes": [
{"action":"set_kernel_profile","value":"safe"},
{"action":"set_build_jobs","value":4}
],
"rationale": [
{"action":"set_kernel_profile","reason":"stability over novelty","evidence":["proven boot uses gentoo-kernel-bin"]},
{"action":"set_build_jobs","reason":"16 GiB RAM","evidence":["memory_mib=16384"]}
]
}"#;
#[test]
fn proposal_file_is_reviewed_and_applied() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("proposal.json");
std::fs::write(&path, PROPOSAL).unwrap();
let mut config = InstallConfig::default();
let outcome = review_file(&mut config, &path).unwrap();
assert_eq!(outcome.applied.len(), 2);
assert_eq!(config.kernel.profile, phoebus_core::KernelProfile::Safe);
assert_eq!(config.packages.build_jobs, Some(4));
}
#[test]
fn chat_response_is_unwrapped() {
let transport = TestTransport::proposal(PROPOSAL);
let mut config = InstallConfig::default();
let outcome = review_response(&mut config, &transport.response).unwrap();
assert_eq!(outcome.applied.len(), 2);
}
#[test]
fn invalid_proposal_leaves_config_unchanged() {
let bad = r#"{"version":1,"changes":[{"action":"set_hostname","value":"bad host"}],"rationale":[{"action":"set_hostname","reason":"x"}]}"#;
let mut config = InstallConfig::default();
assert!(review_proposal_text(&mut config, bad).is_err());
assert_eq!(config.system.hostname, "phoebus");
}
#[test]
fn generate_uses_the_same_review_path() {
use phoebus_core::hardware::HardwareReport;
let facts = SystemFacts::from_system(
&InstallConfig::default(),
&HardwareReport::default(),
&std::collections::HashMap::new(),
true,
None,
);
let transport = TestTransport::proposal(PROPOSAL);
let mut config = InstallConfig::default();
let outcome =
generate_and_review(&mut config, &facts, ProviderKind::DeepSeek, "", &transport)
.unwrap();
assert_eq!(outcome.applied.len(), 2);
}
}

View file

@ -144,23 +144,13 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
None
};
// High-risk operations are preceded by a snapshot when the root is Btrfs.
if action.risk() == phoebus_core::action::Risk::High && cli.root.join(".snapshots").is_dir() {
if let Some(auth) = auth.as_ref() {
match phoebus_executor::snapshot::create_and_record(
&exec,
auth,
&cli.root,
"/",
&action.describe(),
) {
Ok(record) => println!("created snapshot: {}", record.id),
Err(e) => eprintln!("warning: could not create snapshot: {e}"),
}
}
}
// `actions::execute` creates a protective snapshot for high-risk actions
// and fails closed when the snapshots subvolume exists but creation fails,
// so there is a single, tested safety path.
let outcome = actions::execute(&exec, &action, auth.as_ref(), &cli.root)?;
if let Some(id) = &outcome.snapshot {
println!("protective snapshot: {id}");
}
println!("{}", outcome.output);
Ok(())
}

View file

@ -1,5 +1,6 @@
//! Phoebus installer orchestration and CLI support.
pub mod ai_guide;
pub mod orchestrate;
pub mod release;

View file

@ -9,6 +9,7 @@ use std::path::PathBuf;
use std::process::ExitCode;
use clap::Parser;
use phoebus_ai::provider::ProviderKind;
use phoebus_core::{InstallConfig, Redactor, SecretString};
use phoebus_executor::{
authorize, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner,
@ -76,6 +77,30 @@ struct Cli {
/// Fetch and verify the pinned OpenCode release, then exit.
#[arg(long)]
bootstrap_opencode: bool,
/// Enable AI-assisted optimization (opt-in). The facts sent are shown first.
#[arg(long)]
ai: bool,
/// AI provider: `deepseek`, `openai`/`chatgpt`, or `none`.
#[arg(long, value_name = "PROVIDER")]
ai_provider: Option<String>,
/// Model name override for the selected provider.
#[arg(long, value_name = "MODEL")]
ai_model: Option<String>,
/// Read the provider API key from a mode-0600 file (never stored in config).
#[arg(long, value_name = "FILE")]
ai_api_key_file: Option<PathBuf>,
/// Apply a proposal from a file (a chat response or a bare proposal JSON).
#[arg(long, value_name = "FILE")]
ai_proposal_file: Option<PathBuf>,
/// Print the system facts that would be sent to the model, then exit.
#[arg(long)]
ai_facts: bool,
}
struct TerminalConfirm;
@ -111,6 +136,71 @@ fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
}
/// The provider selected on the command line, or the one the TUI/config chose.
fn resolve_provider(
cli: &Cli,
config: &InstallConfig,
) -> std::result::Result<ProviderKind, Box<dyn std::error::Error>> {
let raw = cli
.ai_provider
.as_deref()
.unwrap_or(config.ai.provider.as_str());
ProviderKind::parse(raw)
.ok_or_else(|| format!("unknown AI provider `{raw}` (use deepseek, openai or none)").into())
}
/// Apply AI guidance to the configuration before the plan is shown or install
/// runs. The model never sees secrets and never executes anything: its response
/// is reviewed with mandatory evidence and applied atomically.
fn run_ai_guidance(
cli: &Cli,
installer: &mut Installer,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let provider = resolve_provider(cli, &installer.config)?;
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
if !wants_ai {
return Ok(());
}
if let Some(path) = &cli.ai_proposal_file {
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
println!("{}", outcome.render());
return Ok(());
}
if provider == ProviderKind::None {
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
return Ok(());
}
// Opt-in: show exactly what leaves the machine before sending it.
let facts = installer.system_facts();
eprintln!(
"Sending these system facts to {} (no passwords, passphrases or files):",
provider.as_str()
);
eprintln!("{}", facts.render());
let key_path = cli
.ai_api_key_file
.as_ref()
.ok_or("--ai-api-key-file is required for a live AI provider")?;
let api_key = phoebus_executor::ai::load_api_key(key_path)?;
let model = cli.ai_model.clone().unwrap_or_default();
let transport = phoebus_executor::ai::CurlTransport::new(&installer.exec, api_key);
match phoebus_installer::ai_guide::generate_and_review(
&mut installer.config,
&facts,
provider,
&model,
&transport,
) {
Ok(outcome) => println!("{}", outcome.render()),
Err(e) => eprintln!("AI proposal rejected; continuing with the proven defaults: {e}"),
}
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
@ -183,11 +273,6 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
}
}
if let Some(path) = &cli.save_config {
std::fs::write(path, config.to_toml_string()?)?;
println!("wrote {}", path.display());
}
let mut state_dir = PathBuf::from(&config.runtime.state_dir);
if std::fs::create_dir_all(&state_dir).is_err() {
state_dir = PathBuf::from("/tmp/phoebus-installer");
@ -229,6 +314,17 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
let mut installer = Installer::new(config, exec);
if cli.ai_facts {
println!("{}", installer.system_facts().render());
return Ok(ExitCode::SUCCESS);
}
run_ai_guidance(&cli, &mut installer)?;
if let Some(path) = &cli.save_config {
std::fs::write(path, installer.config.to_toml_string()?)?;
println!("wrote {}", path.display());
}
// Plan / default mode.
if cli.plan || !do_install {
print!("{}", installer.render_plan());

View file

@ -39,8 +39,8 @@ impl Installer {
load_history(&volatile)
};
let engine = PackagePolicyEngine::new().with_history(history);
let binhost_available =
config.packages.binary_packages && !config.stage3.binhost_uri.is_empty();
let binhost_available = config.packages.binary_packages
&& !phoebus_core::system::resolved_binhost_uri(&config).is_empty();
let policy_ctx = PolicyContext {
policy: config.packages.policy,
binhost_available,
@ -76,6 +76,41 @@ impl Installer {
probe::probe_disk_layout(self.exec.runner.as_ref(), &self.config.storage.disk)
}
/// Bounded system facts for AI assistance: hardware, selected profile,
/// signed-binhost availability and measured compile times. No personal
/// data, credentials or file contents.
pub fn system_facts(&self) -> phoebus_ai::provider::SystemFacts {
let persistent = self.exec.root.join("var/lib/phoebus/compile-times.tsv");
let volatile = self.exec.state_dir.join("compile-times.tsv");
let history = if persistent.exists() {
load_history(&persistent)
} else {
load_history(&volatile)
};
let binhost_available = self.config.packages.binary_packages
&& !phoebus_core::system::resolved_binhost_uri(&self.config).is_empty();
let disk = self
.disks
.iter()
.find(|d| d.path == self.config.storage.disk)
.map(|d| phoebus_ai::provider::DiskSummary {
path: d.path.clone(),
size_gib: d.size_bytes / (1024 * 1024 * 1024),
ssd: d
.transport
.as_deref()
.map(|t| t.contains("nvme"))
.unwrap_or(false),
});
phoebus_ai::provider::SystemFacts::from_system(
&self.config,
&self.hardware,
&history,
binhost_available,
disk,
)
}
/// Configuration plus target-disk validation.
pub fn validate(&self) -> Vec<ValidationIssue> {
let mut issues = validate::validate_config(&self.config);

View file

@ -0,0 +1,127 @@
//! End-to-end tests for the AI-assisted path.
//!
//! These run the real binary with `--ai-proposal-file`, which sends a proposal
//! through exactly the same parse -> review (evidence + conflicts) -> apply ->
//! plan path the live provider path uses. Provider fixtures are labelled as
//! such; no test here claims a live provider call.
use std::process::Command;
fn bin() -> &'static str {
env!("CARGO_BIN_EXE_phoebus-installer")
}
fn run_with_proposal(body: &str, extra: &[&str]) -> std::process::Output {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("proposal.json");
std::fs::write(&path, body).unwrap();
let mut cmd = Command::new(bin());
cmd.arg("--ai-proposal-file")
.arg(&path)
.arg("--plan")
.args(extra);
cmd.output().expect("run phoebus-installer")
}
const VALID: &str = r#"{
"version": 1,
"changes": [
{"action":"set_kernel_profile","value":"safe"},
{"action":"set_build_jobs","value":4}
],
"rationale": [
{"action":"set_kernel_profile","reason":"stability over novelty","evidence":["the proven boot uses gentoo-kernel-bin"]},
{"action":"set_build_jobs","reason":"16 GiB RAM","evidence":["memory_mib=16384"]}
]
}"#;
#[test]
fn valid_proposal_is_accepted_and_reaches_the_plan() {
let out = run_with_proposal(VALID, &[]);
assert!(out.status.success(), "{:?}", out);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Accepted AI changes"), "{stdout}");
assert!(stdout.contains("kernel profile = safe"), "{stdout}");
assert!(
stdout.contains("reason: stability over novelty"),
"{stdout}"
);
// The canonical plan reflects the change.
assert!(stdout.contains("gentoo-kernel-bin"), "{stdout}");
}
#[test]
fn missing_evidence_is_rejected() {
let body = r#"{
"version": 1,
"changes": [{"action":"set_hostname","value":"box"}],
"rationale": []
}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("reason"));
}
#[test]
fn conflicting_changes_are_rejected() {
let body = r#"{
"version": 1,
"changes": [
{"action":"set_hostname","value":"one"},
{"action":"set_hostname","value":"two"}
],
"rationale": [
{"action":"set_hostname","reason":"a"},
{"action":"set_hostname","reason":"b"}
]
}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("conflicting"));
}
#[test]
fn malicious_proposal_is_refused() {
let body = r#"{"version":1,"changes":[{"action":"run_shell","command":"rm -rf /"}]}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("invalid") || err.contains("unknown"), "{err}");
}
#[test]
fn invalid_value_is_refused() {
let body = r#"{
"version": 1,
"changes": [{"action":"set_hostname","value":"bad host"}],
"rationale": [{"action":"set_hostname","reason":"x"}]
}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
}
#[test]
fn no_ai_fallback_still_prints_a_plan() {
let out = Command::new(bin())
.arg("--plan")
.output()
.expect("run phoebus-installer --plan");
assert!(out.status.success());
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Installation plan"));
assert!(!stdout.contains("Accepted AI changes"));
}
#[test]
fn ai_facts_are_printed_without_a_provider() {
let out = Command::new(bin())
.arg("--ai-facts")
.output()
.expect("run phoebus-installer --ai-facts");
assert!(out.status.success(), "{:?}", out);
let stdout = String::from_utf8_lossy(&out.stdout);
// The approved fact set is JSON and contains no personal path.
assert!(stdout.trim_start().starts_with('{'), "{stdout}");
assert!(stdout.contains("gentoo_profile"));
assert!(!stdout.contains("/home/"), "{stdout}");
}

View file

@ -55,6 +55,7 @@ enum Choice {
KernelProfile,
PackagePolicy,
DesktopProfile,
AiProvider,
}
enum Mode {
@ -123,6 +124,14 @@ impl App {
}
.into(),
),
(
"AI assistant".into(),
if c.ai.enabled && !c.ai.provider.is_empty() {
c.ai.provider.clone()
} else {
"none".into()
},
),
("Review plan".into(), String::new()),
("Install".into(), String::new()),
("Exit".into(), String::new()),
@ -194,9 +203,10 @@ impl App {
self.mode =
Mode::Edit(self.edit("User password", "", EditTarget::UserPassword, true))
}
14 => self.mode = Mode::Plan(self.render_plan(), 0),
15 => self.mode = Mode::ConfirmErase,
16 => self.mode = Mode::Message("__exit__".into()),
14 => self.mode = Mode::Choice(Choice::AiProvider, 0),
15 => self.mode = Mode::Plan(self.render_plan(), 0),
16 => self.mode = Mode::ConfirmErase,
17 => self.mode = Mode::Message("__exit__".into()),
_ => {}
}
}
@ -390,6 +400,7 @@ fn choice_options(choice: Choice, _config: &InstallConfig) -> Vec<String> {
DesktopProfile::Minimal.to_string(),
DesktopProfile::Full.to_string(),
],
Choice::AiProvider => vec!["none".into(), "deepseek".into(), "openai".into()],
}
}
@ -442,6 +453,17 @@ fn apply_choice(choice: Choice, index: usize, config: &mut InstallConfig) {
DesktopProfile::Full,
][index.min(3)];
}
Choice::AiProvider => {
let provider = ["none", "deepseek", "openai"][index.min(2)];
config.ai.provider = provider.to_string();
config.ai.enabled = provider != "none";
if config.ai.enabled && config.ai.model.is_empty() {
config.ai.model = match provider {
"deepseek" => "deepseek-chat".to_string(),
_ => "gpt-4o-mini".to_string(),
};
}
}
}
}
@ -600,4 +622,16 @@ mod tests {
apply_choice(Choice::Encryption, 1, &mut config);
assert_eq!(config.encryption.mode, Encryption::None);
}
#[test]
fn ai_provider_choice_enables_and_defaults_the_model() {
let mut config = InstallConfig::default();
apply_choice(Choice::AiProvider, 1, &mut config);
assert_eq!(config.ai.provider, "deepseek");
assert!(config.ai.enabled);
assert_eq!(config.ai.model, "deepseek-chat");
apply_choice(Choice::AiProvider, 0, &mut config);
assert_eq!(config.ai.provider, "none");
assert!(!config.ai.enabled);
}
}

View file

@ -119,7 +119,8 @@ def do_boot():
r"phoebus login:"], timeout=60) == 0:
break
child.sendline(checks)
child.expect("===CHECKS-END===", timeout=180)
checks_timeout = int(os.environ.get("CHECKS_TIMEOUT", "180"))
child.expect("===CHECKS-END===", timeout=checks_timeout)
print("checks complete", flush=True)
finally:
child.close(force=True)