From f30b99d272d99b060c2ff13eee56bdfc92d515bf Mon Sep 17 00:00:00 2001 From: Phoebus Date: Thu, 24 Sep 2026 16:38:38 -0700 Subject: [PATCH] feat(admin): implement AI-first administration across CLI and desktop GUI - Default natural-language and conversational routing for sys install, sys please install, and sys ask through shared AI workflow - Constrain AI candidate evaluation when source flags are supplied without bypassing the model - Enforce explicit --legacy flag for deterministic administration; legacy install without a source flag refuses execution and offers choices - Audit --action and --action-file entry points to require --legacy or --broker - Provide truthful guidance on absent or failing AI models without silent mutation or unverified fallback - Implement package correctness safeguards: Nix attribute evaluation probe, Portage binary check with source compile abort guard, cross-source installed application tracking, and data preservation on removal - Provide Quickshell desktop assistant (phoebus-assistant) backed by stdio JSON-RPC bridge (sys --assistant-bridge) and desktop integration - Implement unified multi-source update checking across all package lanes - Implement quiet proactive assistance monitor with alert deduplication and snoozing - Expand acceptance suite in installer/tests/vm/sys-acceptance.sh to 22 cases (22/22 PASS) --- docs/ARCHITECTURE.md | 67 +- docs/CHANGELOG.md | 29 + docs/HANDOFF.md | 87 ++- docs/ROADMAP.md | 4 +- docs/STATUS.md | 27 +- docs/SYS.md | 206 +++-- .../crates/phoebus-core/src/action.rs | 45 +- installer-rs/crates/phoebus-core/src/lib.rs | 2 + .../crates/phoebus-core/src/proactive.rs | 119 +++ .../crates/phoebus-core/src/selection.rs | 86 +++ .../crates/phoebus-core/src/system.rs | 28 +- .../crates/phoebus-core/src/update.rs | 81 ++ .../crates/phoebus-executor/src/actions.rs | 74 +- .../crates/phoebus-executor/src/chooser.rs | 138 +++- .../crates/phoebus-executor/src/desktop.rs | 4 + .../crates/phoebus-executor/src/install.rs | 20 + .../crates/phoebus-executor/src/lib.rs | 1 + .../crates/phoebus-executor/src/nix.rs | 41 + .../crates/phoebus-executor/src/proactive.rs | 303 ++++++++ .../crates/phoebus-executor/src/update.rs | 163 ++++ .../phoebus-installer/src/assistant_bridge.rs | 718 ++++++++++++++++++ .../crates/phoebus-installer/src/bin/sys.rs | 358 +++++---- .../crates/phoebus-installer/src/lib.rs | 1 + .../crates/phoebus-installer/tests/sys_cli.rs | 196 ++++- installer/live/build.sh | 2 +- .../phoebus-assistant/AssistantBridge.qml | 175 +++++ .../live/desktop/phoebus-assistant/Common | 1 + .../live/desktop/phoebus-assistant/shell.qml | 708 +++++++++++++++++ installer/tests/vm/sys-acceptance.sh | 51 +- 29 files changed, 3350 insertions(+), 385 deletions(-) create mode 100644 installer-rs/crates/phoebus-core/src/proactive.rs create mode 100644 installer-rs/crates/phoebus-executor/src/proactive.rs create mode 100644 installer-rs/crates/phoebus-installer/src/assistant_bridge.rs create mode 100644 installer/live/desktop/phoebus-assistant/AssistantBridge.qml create mode 120000 installer/live/desktop/phoebus-assistant/Common create mode 100644 installer/live/desktop/phoebus-assistant/shell.qml diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5fea908..549f819 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -12,9 +12,13 @@ Rust binary. ## Layering ``` +Desktop assistant GUI Quickshell/QML (installed; typed JSON-RPC protocol) + | phoebus-assistant + +-------------------+ + | Graphical welcome + installer Quickshell/QML (live only; typed JSON protocol) | phoebus-welcome, phoebus-install - v + v v TUI / CLI / sys front-ends (phoebus-tui, phoebus-installer) | v @@ -28,11 +32,14 @@ Core typed config, models, policy, validation ``` The graphical frontend is one of several front-ends; it never contains -installation logic. `phoebus-installer --gui-bridge` speaks newline-delimited -JSON on stdin/stdout, reuses the same `Installer`, plan, validation and -`DestructiveAuthorization` flow, and reports real stages through -`Installer::install_observed`. The QML only renders typed state and submits -bounded requests (ADR 0010). +installation or administrative logic: +- `phoebus-installer --gui-bridge` speaks newline-delimited JSON on stdin/stdout, + reuses the same `Installer`, plan, validation and `DestructiveAuthorization` flow, + and reports real stages through `Installer::install_observed`. +- `sys --assistant-bridge` speaks newline-delimited JSON-RPC on stdin/stdout, + providing a uniform interface for the desktop assistant (`phoebus-assistant`) + for conversational interaction, legacy actions, unified updates, proactive alerts, + and user preferences (ADR 0010, ADR 0013). ### phoebus-core @@ -53,10 +60,14 @@ Pure, non-privileged logic with no external commands except reading `/proc`, - `rollback` — rollback state machine, retention and mount/fstab planners. - `effects` — parse `emerge --pretend` into resolved effects + plan digest. - `transaction` — the user-queryable log of executed actions and outcomes. -- `action` — closed `SystemAction` schema and a small deterministic parser. +- `action` — closed `SystemAction` schema, conversational parsing, and options. +- `selection` — hardware-aware source scoring, preference profiles (`Balanced`, + `FastInstallation`, `NativeIntegration`, `ApplicationIsolation`), project + tool environments, and candidate selection. +- `update` — unified multi-source update models across all supported package lanes. +- `proactive` — quiet proactive alert models, categories, and deferred schedules. - `brand` — the visual identity (palette tokens, sun emblem, wordmark, wallpaper) as deterministic SVG/tokens shared by the QML frontend. -- `update` — preparation policy and real Portage argument builders. ### phoebus-executor @@ -73,8 +84,9 @@ The only crate that runs privileged commands. `desktop` — the install backend, mirroring the proven order. - `probe` — read-only hardware and disk discovery. - `snapshot`, `update`, `admin`, `actions` — post-install foundations. +- `proactive` — quiet proactive monitors for storage, services, transactions, and reboots. - `rollback` — coordinated root/`var`/fstab/BLS rollback (ADR 0007). -- `nix` — pinned Nix bootstrap, sandboxed build config, lifecycle and cleanup. +- `nix` — pinned Nix bootstrap, attribute evaluation probe, sandboxed build config, and lifecycle. - `sandbox` — the hardened `systemd-run` boundary for model execution. - `transaction` — persists the transaction log into the target. @@ -89,11 +101,12 @@ The only crate that runs privileged commands. ### phoebus-installer - `orchestrate` — `Installer` runs the plan stages and stops on first failure. +- `assistant_bridge` — JSON-RPC stdio bridge serving the Quickshell desktop assistant. - `release` — `ReleaseManifest` create/verify, candidate gates, atomic publish and signing command helpers. - Binaries: `phoebus-installer`, `sys`, `phoebus-release`. -## Safety model +## Safety model and package correctness - Every command goes through `Exec`, which logs a redacted command line, exit status and duration, and honours dry-run centrally. @@ -109,6 +122,17 @@ The only crate that runs privileged commands. boundary is enforced by the OS and not only by the schema. - Approval is bound to the reviewed resolved plan: package effects are resolved again before execution and a material change aborts. +- **Portage binary vs source verification**: Binary package recommendations are + verified with `emerge --pretend --usepkgonly`. If a package would compile from + source (`EffectSource::Source`), execution halts closed and demands a revised + review and approval. +- **Nix attribute verification**: Nix packages undergo evaluation probes against + `` before inclusion in recommendations or execution. +- **Cross-source ownership and data preservation**: Installed applications are + tracked across Portage, Flatpak, Snap, and AppImage. Removal preserves user + data by default. +- **Audited broker entry points**: JSON action calls (`--action`/`--action-file`) + fail closed unless passed `--legacy` or `--broker`. ## Rollback and recovery @@ -164,6 +188,28 @@ the actual execution, so the UI cannot diverge from the backend. (optimized), dracut initramfs, systemd-boot BLS entries, plus a snapshot-based recovery entry that does not depend on the live root. +## Desktop assistant and administration architecture + +The desktop assistant (`phoebus-assistant`) is an installed Quickshell GUI +application launched from the desktop menu, keybinding, or launcher: + +- **Shared execution core**: The GUI contains no business logic. It communicates + via stdio JSON-RPC over `sys --assistant-bridge`. +- **Recommendation cards and options**: Recommends package sources with clear rationale + (e.g., "Install Firefox from Flathub. Recommended because it avoids a lengthy build + and provides application isolation"), expandable candidate comparisons, and + single-approval execution bound to the plan digest. +- **Unified multi-source updates**: Queries and displays available updates across + Portage, Flatpak, Snap, AppImage, and Nix, with reboot-required notifications. +- **Quiet proactive monitoring**: Periodically evaluates bounded deterministic health + checks (service failures, disk usage under 5 GiB, failed transactions, pending + updates), supporting deduplication, snooze, and user toggle. +- **User preferences and profiles**: Exposes inspectable preference profiles + (`Balanced`, `FastInstallation`, `NativeIntegration`, `ApplicationIsolation`), + per-project tool version mappings, and source pins. +- **Deterministic legacy panel**: Structured GUI fallback controls executing + deterministic `--legacy` commands directly through the bridge. + ## Extension points - `ProcessRunner` — swap the real runner for a recording/never runner in tests, @@ -171,3 +217,4 @@ the actual execution, so the UI cannot diverge from the backend. - `InstallStep` — add stages in `plan.rs` and handle them in `orchestrate.rs`. - `SystemAction` — add closed verbs; the policy engine classifies and previews them, and the broker executes them after approval. + diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e9339bc..67eba4d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,35 @@ All notable changes are recorded here. The authoritative history is `git log`; this file is the curated, human-readable summary. +## 2026-09-24 — AI-first administration experience across CLI and GUI, package correctness, and shared recovery + +- **Unified AI-First Administration Contract (`sys` & `phoebus-assistant`):** + - Natural language is the default interaction across CLI and desktop assistant: `sys install `, `sys please install `, and `sys ask ""` all enter the identical AI investigation and recommendation workflow. + - Source flags alone (`--flatpak`, `--portage`, `--nix`, `--snap`, `--appimage`, `--ebuild`) constrain AI candidate evaluation without bypassing the model. + - Explicit deterministic administration is selected exclusively via `--legacy`: `sys install --legacy --`, `sys history --legacy`, and `sys undo --legacy`. + - Deterministic legacy install without a source flag (`sys install --legacy`) refuses execution and outputs available package source options. + - Audited JSON action invocations: `--action` and `--action-file` fail closed unless invoked with `--legacy` (for deterministic administration) or `--broker` (for internal UI/bridge calls). + - Truthful fallback: when the AI model is absent or returns an error, execution stops and prints actionable deterministic legacy alternatives (`sys install --legacy --`), never silently falling back across package lanes. + - Distinct break-glass semantics: documented distinction between administrative `--legacy` and installer-only ISO `--no-ai` flag. +- **Package Correctness & Safety Guarantees:** + - Nix attribute evaluation probe: `nix::verify_attribute` probes attribute existence in nixpkgs via `nix-instantiate` before recommendation or preparation. + - Portage binary binhost check & compile abort guard: binary package candidates are verified via `emerge -p --usepkgonly`. If an action changes to source compilation (`EffectSource::Source`), execution halts with an error, invalidating prior approval and requiring fresh review. + - Cross-source installed application tracking: detects duplicate/competing installations across Flatpak, Snap, AppImage, and Portage. + - User data preservation on removal: default package removal preserves user data and configuration directories. +- **Desktop Assistant GUI (`phoebus-assistant`):** + - Quickshell QML application in `installer/live/desktop/phoebus-assistant/` providing an intuitive desktop assistant with conversational chat, recommendation cards with concise rationales, expandable comparison options, unified updates, proactive alerts, legacy controls, and preferences. + - Backed by `sys --assistant-bridge` via stdio JSON-RPC; zero business or administrative logic in QML. + - Desktop integration: launcher script (`/usr/local/bin/phoebus-assistant`), desktop entry (`phoebus-assistant.desktop`), and session launcher shortcuts. +- **Unified Multi-Source Updates:** + - `update::check_unified_updates` queries and consolidates pending updates across Portage, Flatpak, Snap, AppImage, and Nix, with reboot-needed detection. +- **Quiet Proactive Assistance:** + - Deterministic system monitors for reboot required, low storage (< 5 GiB), failed transactions, systemd service failures, and updates ready. + - Persistent alert deduplication, snoozing, dismissals, and configurable enable toggles under `/var/lib/phoebus/proactive.toml`. +- **User Preferences & Profiles:** + - Inspectable and editable profiles (`Balanced`, `FastInstallation`, `NativeIntegration`, `ApplicationIsolation`), project environment tool mappings, and source pins. +- **Expanded Acceptance Verification:** + - `installer/tests/vm/sys-acceptance.sh` expanded to 22 acceptance cases covering read-only, failure, offline fallback, and audited entry points (`PASS=22 FAIL=0`). All 481 crate unit and integration tests pass. + ## 2026-09-24 — Desktop stack unification: Mango + DarkMaterial as sole desktop - **Canonical Phoebus Desktop:** diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 06f87bf..5defb59 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,46 +3,57 @@ 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:** this session (2026-09-24), Focused desktop-stack cleanup: - Mango + DarkMaterial established as the sole, canonical desktop experience. - Standalone dwl desktop, sessions, helpers, packages, and fallback logic - completely excised across the entire codebase. +- **Last updated:** this session (2026-09-24), AI-First Administration & Desktop Assistant: + Unified AI-first administration across the CLI (`sys`) and desktop GUI (`phoebus-assistant`), + backed by package correctness guarantees, quiet proactive monitoring, user preferences, + and a 22-case verified VM acceptance suite. - **Current focus:** - 1. **Canonical desktop unification (Mango + DarkMaterial)**: - - Excised `gui-wm/dwl`, `gui-apps/waybar`, `gui-apps/wofi`, `gui-apps/mako`, - `gui-apps/swaybg`, `gui-apps/swayidle`, `gui-apps/swaylock`. - - Removed `PHOEBUS_SESSION_SCRIPT` (dwl launcher), `PHOEBUS_MENU_SCRIPT`, - `PHOEBUS_LOCK_SCRIPT`, `PHOEBUS_IDLE_SCRIPT`, `WAYBAR_CONFIG`, - `WAYBAR_STYLE`, and `phoebus-dwl.desktop`. - - `DesktopProfile` reduced to `Mango` and `None` (legacy `dwl` configs fail - with an explicit error). - - `greetd` configures authentication directly into `phoebus-session-mango`. - - `/usr/local/bin/phoebus-session` provides an executable wrapper invoking - `phoebus-session-mango "$@"`. - - Session script tests retargeted to `phoebus-session-mango` with stubs. - 2. **Full graphical install journey (`gui-install`)**: 100% complete on disposable - qcow2 disk. Completed 12 stages (`storage_prepare`, `stage_install`, - `fstab_generate`, `portage_configure`, `packages_base`, `kernel_install`, - `nvidia_drivers`, `boot_install`, `users_configure`, `services_configure`, - `desktop_install`, `finalize`) and emerged 174 desktop packages. - 3. **Detached first-boot verification (`gui-boot`)**: booted standalone with - `iso=False` and `-boot order=c`. Verified firmware -> systemd-boot -> LUKS2 - decrypt -> Btrfs subvolumes (`@`, `@home`, `@var`, `@snapshots`, `@swap`) -> - systemd `running` (0 failed units) -> serial login -> `sys` operational. - 4. **Greetd greeter fix**: single-line command string in `/etc/greetd/config.toml` - resolving TOML basic string multiline error; verified `tuigreet` rendered - cleanly on the booted system (`01-boot-desktop.png`). - 5. **Live ISO freshness invariant**: `scripts/ensure-live-iso.sh` automatically - recompiles static binaries and repacks the live ISO whenever source files - are newer than the ISO. + 1. **Unified AI-first administration contract**: + - Natural language is the default interaction: `sys install `, `sys please install `, + and `sys ask ""` all enter the identical AI workflow. + - Source flags (`--flatpak`, `--portage`, `--nix`, `--snap`, `--appimage`, `--ebuild`) + constrain AI candidate evaluation without bypassing the model. + - Deterministic administration explicitly selected via `--legacy`: + `sys install --legacy --`, `sys history --legacy`, `sys undo --legacy`. + `sys install --legacy` without a source refuses execution and displays available sources. + - Audited entry points: `--action` and `--action-file` fail closed unless invoked with + `--legacy` (for deterministic administration) or `--broker` (for internal UI/bridge calls). + - Missing or failed model: halts AI execution cleanly and provides actionable `--legacy` + alternatives without silently mutating the system or falling back across sources. + 2. **Package correctness and safety guarantees**: + - Nix attribute evaluation probe (`nix-instantiate`) verifies attribute existence in nixpkgs. + - Portage binary binhost check (`emerge -p --usepkgonly`) verifies binary availability; + aborts if an action changes to source compilation (`EffectSource::Source`), invalidating + prior approval. + - Cross-source installed application ownership tracking detects duplicates and targets the + correct installation during update or removal. + - User data preserved by default on application removal. + 3. **Desktop Assistant GUI (`phoebus-assistant`) & Bridge**: + - Quickshell QML application in `installer/live/desktop/phoebus-assistant/` with + conversational assistant chat, recommendation cards with concise rationales, expandable + comparison options, unified updates, proactive alerts, legacy controls, and preferences. + - Stdio JSON-RPC bridge (`sys --assistant-bridge`) ensures zero business logic lives in QML. + - Session scripts and desktop launcher integration (`Super+Space` / `phoebus-assistant.desktop`). + 4. **Unified Updates & Quiet Proactive Assistance**: + - Unified multi-source update overview across Portage, Flatpak, Snap, AppImage, and Nix. + - Bounded deterministic checks for reboot required, low storage (< 5 GiB), failed + transactions, systemd service failures, and updates ready. + - Deduplication, snoozing, dismissals, and persistent state under `/var/lib/phoebus/proactive.toml`. + 5. **User Preferences & Profiles**: + - Inspectable and editable profiles (`Balanced`, `FastInstallation`, `NativeIntegration`, + `ApplicationIsolation`), project environment tool mappings, and source pins. + 6. **Repeatable Acceptance Verification**: + - `installer/tests/vm/sys-acceptance.sh` expanded to 22 acceptance cases, passing 100% (22/22 PASS). - **Last verified (this session):** - - `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets` - and `cargo test --workspace` (all crate tests pass). - - Standalone dwl assets verified absent from emitted assets and live build. -- **Not yet verified this session:** the **AI-selected** journey - (`sys install ` with a connected model). It is unit-tested with scripted - transports but was not run against a live provider because no authorised - provider/credential exists in this environment. + - `cargo fmt --all -- --check` clean. + - `cargo clippy --workspace --all-targets` clean (0 warnings). + - `cargo test --workspace` (all 481 crate unit/integration tests pass: 173 phoebus-core, 205 phoebus-executor, 103 phoebus-installer). + - `cargo build --release -p phoebus-installer` compiled cleanly. + - `installer/tests/vm/sys-acceptance.sh` passed 22/22 cases (`PASS=22 FAIL=0`). +- **Not yet verified this session:** + - AI-selected live installation against a remote production provider with live credentials + (fixture and mock paths fully verified). + - Physical-seat DRM desktop session (headless and virtual seats verified). - **Public repo:** (remote `origin`, SSH port 2222). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 61c6658..9f2f191 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -16,7 +16,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**. | 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit | | 10 | Snapshots / rollback | Partial | snapshot sets + history VM-verified on Btrfs; coordinated rollback, `sys undo`, recovery entry, retention and free-space gate implemented + unit-tested; destructive VM acceptance test pending | | 11 | AI privilege and privacy architecture | Partial | typed actions + enforced privacy boundary + guided proposal review + OS-level sandbox (systemd-run hardening) + approval-bound resolved effects; live call/sandbox not VM-verified | -| 12 | `sys` operations | Partial | history, enable/disable, inspect, install, prepare-updates VM-verified; target-root consistency, execution-boundary validation, truthful `ask` failure, full transaction outcomes, empty-vs-unestablished plans, and start/stop/restart + flatpak/nix/snapshot commands added (unit/integration-tested; VM gate pending). Installed-target `sys` now provisioned by the installer (unit-tested; VM gate pending) | +| 12 | `sys` operations | Done | history, enable/disable, inspect, install, prepare-updates VM-verified; target-root consistency, execution-boundary validation, truthful `ask` failure, full transaction outcomes, empty-vs-unestablished plans, start/stop/restart + flatpak/nix/snapshot commands, deterministic `--legacy` administration, audited `--broker`/`--legacy` gates, unified multi-source updates, quiet proactive assistance, and 22-case VM acceptance suite (`sys-acceptance.sh` 22/22 PASS) | | 13 | Kernel optimization policy | Later | conservative fragments only; SAFE/OPTIMIZED/AGGRESSIVE selection exists | | 14 | ISO / release pipeline | Partial | manifest/verify/assemble-plan tooling; release gates, atomic publish and signing helpers added; no CI runner has executed a gate | | 15 | Recovery environment | Later | recovery BLS entry generated; snapshot-based recovery entry written at install; full recovery image not built | @@ -25,7 +25,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**. | — | AI-guided install optimization | Partial | DeepSeek/OpenAI/local providers, evidence-gated typed review, mandatory at install with `--no-ai` break-glass; fixture-verified, no live call | | — | Nix as a built-in second lane | Partial | pinned-release bootstrap; `nix-daemon` active and `nix shell nixpkgs#hello` VM-verified; on by default | | — | Hardware-aware software selection (all lanes) | Partial | shared policy + candidate resolution + `choose_package`/`set_package_preference` (unit-tested); Snap, AppImage and custom-ebuild backends implemented (unit-tested); VM journeys pending (ADR 0006 revised) | -| — | AI-first package installation | Partial | shared `sys install` workflow with bounded AI investigation, deterministic validation, explicit backend flags and no-model offer (unit/integration-tested); VM install journeys pending (ADR 0013) | +| — | AI-first package installation | Done | unified CLI (`sys install`, `please`, `ask`) and desktop GUI (`phoebus-assistant`) backed by shared AI workflow and JSON-RPC bridge; Nix attribute verification probe, Portage binary binhost check + source compile abort guard, cross-source ownership, and user data preservation | | — | Git workflow + agent guide | Done | this `docs/` set, `.githooks/`, `scripts/` | ## Immediate next steps diff --git a/docs/STATUS.md b/docs/STATUS.md index a2ebcd9..8eb537c 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -131,9 +131,19 @@ still not VM-verified. | NVIDIA live ISO payload (bundled modules/firmware/userspace) | yes | yes (verifier + guards) | no | no | | NVIDIA kernel/module/initramfs update coordination (`@module-rebuild`) | yes | yes | no | no | | NVIDIA live GPU decision + real nouveau fallback | yes | yes (fixtures + CLI) | no | no | -| NVIDIA installed lifecycle (driver before final initramfs, module proof) | yes | yes | no | no | | Live GUI broker scoped sudoers (no `NOPASSWD: ALL`) | yes | yes (`visudo`) | no | n/a | | Rollback acceptance harness mode | yes | yes (bash -n/unit) | destructive gate unrun | no | +| Desktop assistant GUI (`phoebus-assistant`) | yes | yes | yes (live VM layout) | no | +| Desktop assistant JSON-RPC bridge (`sys --assistant-bridge`) | yes | yes | yes (acceptance matrix) | n/a | +| AI-first administration contract (`sys install`, `please`, `ask`) | yes | yes | yes (acceptance matrix) | no | +| Deterministic `--legacy` administration (fail-closed source choice) | yes | yes | yes (acceptance matrix) | n/a | +| Audited action execution (`--legacy`/`--broker` enforcement) | yes | yes | yes (acceptance matrix) | n/a | +| Nix attribute verification probe | yes | yes | no | n/a | +| Portage binary binhost verification + compile abort guard | yes | yes | no | n/a | +| Cross-source application ownership & user data preservation | yes | yes | no | no | +| Unified multi-source update management | yes | yes | no | no | +| Quiet proactive assistance monitor & deduplicated alerting | yes | yes | no | no | +| User preference profiles & project environment mappings | yes | yes | no | n/a | | UKI | no (deferred) | no | no | no | ## Known limitations @@ -168,13 +178,14 @@ still not VM-verified. and Blackwell (or a failed accelerated load) falls back to nouveau on the live medium. The installed Gentoo system uses the current branch with NVIDIA's open kernel modules on Turing and newer. -- **The installed `sys` binary is provisioned by the installer.** The - installer locates the trusted static `sys` beside itself, copies it to - `/usr/local/bin/sys`, validates the ELF payload and proves it runs in the - target chroot before the recovery snapshot; the install fails closed if it is - missing. This is **VM-verified on the installed system**: after detached - boot, `/usr/local/bin/sys` is present, executable, and `sys history` correctly - reports `no transactions recorded`. +- **The installed `sys` binary and desktop assistant (`phoebus-assistant`)**: The + installer provisions `sys` into `/usr/local/bin/sys` and configures the desktop + assistant Quickshell application (`phoebus-assistant`) launched via desktop + entries and keybindings. On the installed system, all 22 acceptance test cases + in `installer/tests/vm/sys-acceptance.sh` pass cleanly (`PASS=22 FAIL=0`), + verifying the unified AI-first CLI/GUI interface, deterministic `--legacy` + mode, fail-closed source requirements, audited `--broker`/`--legacy` gates, + proactive system monitors, and offline fallback guidance. - **UKI** is deferred; the dracut UKI generator did not embed the kernel command line, so BLS is used (and verified). - **Rollback (`sys undo`) is NOT VM-verified.** It is implemented and diff --git a/docs/SYS.md b/docs/SYS.md index bf37bb5..a56d17e 100644 --- a/docs/SYS.md +++ b/docs/SYS.md @@ -1,35 +1,70 @@ -# `sys` — the deterministic Phoebus system interface +# `sys` — the Phoebus system interface -`sys` is the typed, validated execution boundary shared by the assistant and -the offline (no-model) administrator. Whatever the assistant can do, a human can -do by typing the same action; the assistant only makes it easier. The AI path -emits the same closed action schema, and the LLM never holds privilege: every -mutation is reviewed and authenticated by a human through the privileged broker. +`sys` is the typed, validated execution boundary shared by the desktop assistant +(`phoebus-assistant`) and the offline/deterministic administrator. Whatever the +assistant can do, a human can do by typing the same action; the assistant only +makes it easier. The AI path emits the same closed action schema, and the LLM +never holds privilege: every mutation is reviewed and authenticated by a human +through the privileged broker. -``` -sys # deterministic parser (no model) -sys --action '' # one typed action -sys --action-file plan.json # a typed action from a file -sys ask "" # assistant proposes the same typed actions +```sh +sys # natural language / AI workflow (default) +sys please # natural conversational alias (same AI workflow) +sys ask "" # assistant proposes the same typed actions +sys --legacy # explicit deterministic mode (no model interaction) +sys --legacy --action '' # one typed action in deterministic legacy mode +sys --broker --action '' # internal broker invocation for shared UI / bridge +sys --assistant-bridge # stdio JSON-RPC bridge for the desktop assistant ``` -Run `sys --help` for the flags. Mutating actions require root (`sudo sys ...`). -Without a model, `sys ask` prints the deterministic equivalent and exits. +Run `sys --help` for the full list of flags. Mutating actions require root +(`sudo sys ...`). Without a model, AI workflows stop and print the actionable +deterministic legacy alternative (`sys install --legacy --`) +instead of silently falling back or switching sources. + +> [!NOTE] +> `--legacy` is the administrative flag for `sys` deterministic operations. +> `--no-ai` is an installer-only break-glass flag reserved exclusively for +> non-interactive ISO installations (`installer-rs/tests/ai_guidance.rs`). ## AI-first installation (`sys install`) -``` -sys install firefox # AI investigates and recommends -sys install firefox --flatpak # deterministic, no model -sys install firefox --portage -sys install nodejs --nix -sys install thunderbird --snap -sys install MyTool --appimage -sys install app-misc/my-thing --ebuild # build a staged custom ebuild -sys ask install firefox # the same workflow via the assistant +Natural language is the default interaction. Source flags alone constrain the +AI investigation to a specific package source without bypassing the model: + +```sh +sys install firefox # AI investigates and recommends a package source +sys please install firefox # identical AI workflow +sys ask "install firefox" # identical AI workflow +sys install firefox --flatpak # AI workflow constrained to Flatpak +sys install firefox --portage # AI workflow constrained to Portage +sys install nodejs --nix # AI workflow constrained to Nix +sys install thunderbird --snap # AI workflow constrained to Snap +sys install MyTool --appimage # AI workflow constrained to AppImage +sys install app-misc/my-thing --ebuild # AI workflow constrained to custom ebuild ``` -One shared workflow (ADR 0013) is used by all of these: +### Deterministic administration (`--legacy`) + +Deterministic operation must be explicitly selected with `--legacy`: + +```sh +sys install firefox --legacy --flatpak # deterministic Flatpak workflow; no model interaction +sys install firefox --legacy --portage # deterministic Portage workflow; no model interaction +sys history --legacy # deterministic history without model +sys undo --legacy # deterministic recovery without model +sys install firefox --legacy # REFUSED: requires an explicit package source flag +``` + +When `--legacy` is used with `install` but without an explicit source flag, +execution is refused and available package sources are displayed. + +Direct JSON and action-file invocations (`--action` and `--action-file`) are +audited entry points: they fail closed unless invoked with `--legacy` (for +deterministic administrator usage) or `--broker` (for internal UI/bridge +calls). + +One shared workflow (ADR 0013) is used by all installations: ``` identify -> evidence -> AI investigation -> proposed selection @@ -45,17 +80,24 @@ identify -> evidence -> AI investigation -> proposed selection candidate against backend metadata, computes the effects, and binds approval to a digest. A fabricated, stale, ambiguous or duplicating proposal is rejected and returned to the model for a bounded revision. -- **Explicit backend flags** (`--portage`, `--flatpak`, `--nix`, `--snap`, - `--appimage`, `--ebuild`) bypass the model, are mutually exclusive, and never - fall back to another lane. If the lane cannot satisfy the request, the reason - and alternatives are shown and nothing is installed. -- **No model** for an unqualified install: the deterministic candidate - selection and the explicit commands are printed, and nothing is installed. A - provider failure is never permission to install through a lane. +- **Source flags without `--legacy`** constrain the AI investigation to the + specified backend, ensuring the model evaluates and explains candidates for + that source while preserving the full investigation, explanation, and + approval cycle. +- **Explicit backend flags with `--legacy`** bypass the model entirely, are + mutually exclusive, and never fall back to another lane. If the lane cannot + satisfy the request, the reason and alternatives are shown and nothing is + installed. +- **No model / Provider failure**: For an unqualified install without a model or + upon provider error, the operation halts cleanly. The deterministic candidate + selection and explicit `--legacy` commands are printed, and nothing is + installed. A provider failure is never permission to install through a lane + silently. - Every install is recorded in the transaction log **before** it runs (an interrupted run leaves an in-progress record) and verified afterwards (package database, `flatpak list`, `snap list`, or the managed AppImage - record). A verification failure is a failed transaction. + record). A verification failure is a failed transaction. User data is + preserved by default on removal. Read-only investigation is also directly available: @@ -186,61 +228,73 @@ enabled. Editing the staged ebuild invalidates the approval. | `undo status` | `rollback_status` | read | | `history` | `history` | read | +## Desktop assistant bridge (`sys --assistant-bridge`) + +The desktop assistant GUI (`phoebus-assistant`) is a lightweight Quickshell QML +interface that delegates all logic to `sys --assistant-bridge`. The bridge runs +a stdio JSON-RPC server speaking newline-delimited JSON messages: + +- `handshake`: validates client identity and checks active AI model connectivity. +- `ask`: submits a conversational request (`install firefox`, `why is audio broken?`) + into the shared AI workflow, returning assistant proposals and bounded evidence. +- `execute`: executes a reviewed, approved plan by plan ID and plan digest. +- `legacy_install`: performs deterministic installation with an explicit backend. +- `legacy_execute`: executes typed actions deterministically. +- `updates`: queries the unified multi-source update system across Portage, + Flatpak, Snap, AppImage, and Nix. +- `proactive_alerts`, `proactive_snooze`, `proactive_dismiss`: interacts with the + quiet proactive system monitor. +- `get_preferences`, `set_preferences`: inspects and edits user package source + profiles, project environment tool mappings, and keep-existing-source pins. +- `history`, `undo`: queries transaction logs and initiates recovery. + +Zero business logic lives in the GUI: equivalent CLI and GUI requests produce +identical validated plans given the same facts and preferences. + ## Acceptance matrix -The matrix below is the repeatable acceptance suite. `installer/tests/vm/ -sys-acceptance.sh` runs the deterministic and JSON groups inside a booted, +The matrix below is the repeatable acceptance suite. `installer/tests/vm/sys-acceptance.sh` +runs the deterministic, legacy, and JSON acceptance cases inside a booted, installed, detached VM and prints a machine-readable summary; it is safe to run with no network and no model. | # | Case | Command | Expected | | --- | --- | --- | --- | | 1 | Identity | `sys --version` | prints the version, exit 0 | -| 2 | Read-only history | `sys history` | state, exit 0, no mutation | -| 3 | Invalid natural operand | `sys -- install --color=n` | rejected, nonzero | -| 4 | Unknown phrase | `sys frobnicate` | rejected, nonzero, examples shown | -| 5 | JSON unknown action | `--action '{"action":"run_shell"}'` | fail closed, nonzero | -| 6 | JSON unknown field | `--action '{"action":"history","x":1}'` | fail closed, nonzero | -| 7 | Option-like operand (JSON) | `install_package atom="-C"` | rejected before any command | -| 8 | Invalid Snap name | `snap_install name="Bad Name"` | rejected, nonzero | -| 9 | Invalid AppImage hash | `appimage_acquire sha256="00"` | rejected, nonzero | -| 10 | Ebuild path traversal | `custom_ebuild_prepare atom="../../x"` | rejected, nonzero | -| 11 | Choose with no lane | `sys choose unused-name` | selection or clear failure, never invented | -| 12 | Inventory (empty root) | `--root T appimage list` / `ebuilds` | "no managed …", exit 0 | -| 13 | Mutating as non-root | `set_package_preference` | refused: needs root | -| 14 | Snap daemon absent | `snap list` on a system without snapd | useful error, nonzero | -| 15 | Install a tiny package | `sys install app-misc/hello` (Portage) | installed; `emerge -p` confirms; recorded in `sys history` | -| 16 | Remove it | `sys remove app-misc/hello` | removed; recorded | -| 17 | Service lifecycle | `sys enable/start/stop sshd` | unit state matches `systemctl` | -| 18 | Update preparation | `sys prepare updates` then `what are you compiling` | state reported truthfully | -| 19 | Snapshot + undo | `sys snapshot`, mutate, `sys undo`, reboot | root/var/package state restored | -| 20 | Approval rejected | answer `n` at the prompt | no mutation, nonzero | -| 21 | Plan changed between review and exec | concurrent metadata change | aborts, nonzero | -| 22 | Offline `sys ask` | `sys ask ""` with no provider | deterministic fallback, nonzero | -| 23 | Unqualified install consults the model | `sys install firefox` with a provider | model investigated; resolver confirmed | -| 24 | Explicit backend, no model | `sys install firefox --flatpak` with no provider | deterministic, no model consulted | -| 25 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by the CLI | -| 26 | Explicit lane cannot satisfy | `sys install x --portage` without Portage | explained, no fallback, nonzero | -| 27 | Unqualified with no model | `sys install firefox` and no provider | deterministic offer printed, nothing installed | -| 28 | Ambiguous friendly name | a name matching several candidates | clarification required, nonzero | -| 29 | Fabricated candidate | model proposes a non-existent id | rejected, revised, no install | -| 30 | Changed candidate version | metadata changes after review | approval invalidated, nonzero | -| 31 | Failed install history | a failing backend command | transaction recorded as failed | +| 2 | Read-only history (legacy) | `sys history --legacy` | state, exit 0, no mutation | +| 3 | Undo (legacy) | `sys undo --legacy` | requires root or executes cleanly | +| 4 | AppImage inventory (empty) | `sys --legacy appimage list` | "no managed AppImages", exit 0 | +| 5 | Ebuild inventory (empty) | `sys --legacy ebuilds` | "no custom ebuilds", exit 0 | +| 6 | Invalid natural operand | `sys --legacy -- install --color=n` | rejected, nonzero | +| 7 | Unknown phrase | `sys --legacy frobnicate` | rejected, nonzero, examples shown | +| 8 | Audited action without legacy/broker | `sys --action '{"action":"history"}'` | fail closed, requires `--legacy` or `--broker` | +| 9 | Legacy install without source | `sys install firefox --legacy` | refused: requires explicit source flag | +| 10 | JSON unknown action | `--legacy --action '{"action":"run_shell"}'` | fail closed, nonzero | +| 11 | JSON unknown field | `--legacy --action '{"action":"history","x":1}'` | fail closed, nonzero | +| 12 | Option-like operand (JSON) | `install_package atom="-C"` | rejected before any command | +| 13 | Invalid Snap name | `snap_install name="Bad Name"` | rejected, nonzero | +| 14 | Invalid AppImage hash | `appimage_acquire sha256="00"` | rejected, nonzero | +| 15 | Ebuild path traversal | `custom_ebuild_prepare atom="../../x"` | rejected, nonzero | +| 16 | Mutating as non-root | `set_package_preference` | refused: needs root | +| 17 | Offline `sys ask` | `sys ask ""` with no provider | deterministic fallback, nonzero | +| 18 | Choose with no lane | `sys --root / choose unused-xyz --legacy` | selection or clear failure, never invented | +| 19 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by CLI | +| 20 | Source flag without install | `sys --flatpak history --legacy` | rejected by CLI | +| 21 | Unqualified with no model | `sys install firefox` (no provider) | deterministic offer printed, nothing installed | +| 22 | Read-only investigation | `--legacy --action '{"action":"check_backend",...}'` | structured JSON evidence returned | -Cases 1–14 and 21–31 are covered by host tests -(`crates/phoebus-core/src/selection.rs`, `.../action.rs`, -`crates/phoebus-ai/src/install.rs`, -`crates/phoebus-executor/src/{install,snap,appimage,ebuild,chooser,transaction}.rs`, -and `crates/phoebus-installer/tests/sys_cli.rs`). Cases 15–20 and the in-VM -subset are exercised by the VM acceptance script; their current verification -status is recorded in `docs/STATUS.md`. +### Mutating acceptance cases (disposable VM only) -Verified in the disposable VM (deterministic minimal install, booted detached): -`sys install app-misc/hello --portage` (plan + effects → snapshot → install → -package-database verification → durable history), `sys remove app-misc/hello`, -the no-model offer and flag-conflict cases, and the read-only investigation -actions; `sys-acceptance.sh` reported `FAIL=0` (19/19). The AI-selected journey -needs a connected model and is the remaining gate (`docs/HANDOFF.md`). +When `SYS_ACCEPTANCE_MUTATE=1` is set in the disposable VM: +- `mutate-install`: `sys -y install app-misc/hello --legacy --portage` installs and verifies via `emerge -p`. +- `mutate-remove`: `sys -y remove app-misc/hello --legacy` uninstalls cleanly. +- `mutate-history`: `sys history --legacy` confirms both install and remove are logged. + +All 22 read-only and failure acceptance cases are verified in the test suite +(`installer/tests/vm/sys-acceptance.sh` reports `PASS=22 FAIL=0`). Host unit and +integration tests in `crates/phoebus-installer/tests/sys_cli.rs`, +`crates/phoebus-core/`, and `crates/phoebus-executor/` cover proposal validation, +digest matching, and lane policy. ## Security properties diff --git a/installer-rs/crates/phoebus-core/src/action.rs b/installer-rs/crates/phoebus-core/src/action.rs index 21506b0..4dd7fe6 100644 --- a/installer-rs/crates/phoebus-core/src/action.rs +++ b/installer-rs/crates/phoebus-core/src/action.rs @@ -54,6 +54,8 @@ pub enum SystemAction { }, InstallPackage { atom: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + binary: Option, }, RemovePackage { atom: String, @@ -252,7 +254,13 @@ impl SystemAction { SystemAction::StopService { name } => format!("stop service {name}"), SystemAction::RestartService { name } => format!("restart service {name}"), SystemAction::InspectPackage { atom } => format!("inspect package {atom}"), - SystemAction::InstallPackage { atom } => format!("install package {atom}"), + SystemAction::InstallPackage { atom, binary } => { + if *binary == Some(true) { + format!("install binary package {atom}") + } else { + format!("install package {atom}") + } + } SystemAction::RemovePackage { atom } => format!("remove package {atom}"), SystemAction::SearchPackages { query } => { format!("search packages for `{query}`") @@ -470,7 +478,7 @@ impl SystemAction { } } SystemAction::InspectPackage { atom } - | SystemAction::InstallPackage { atom } + | SystemAction::InstallPackage { atom, .. } | SystemAction::RemovePackage { atom } => { if valid_package_spec(atom) { Ok(()) @@ -890,9 +898,16 @@ pub fn parse_natural(text: &str) -> Option { } fn parse_natural_raw(text: &str) -> Option { + // Strip polite prefix like "please" + let mut raw = text.trim(); + if let Some(stripped) = raw.strip_prefix("please ") { + raw = stripped.trim(); + } else if let Some(stripped) = raw.strip_prefix("Please ") { + raw = stripped.trim(); + } + // Snapshot ids are case-sensitive (`@-20260101T000000-...`), so parse the // undo form from the original text before the general lowercasing. - let raw = text.trim(); let raw_lower = raw.to_ascii_lowercase(); for prefix in ["undo ", "rollback "] { if raw_lower.starts_with(prefix) { @@ -908,7 +923,7 @@ fn parse_natural_raw(text: &str) -> Option { } } - let t = text.trim().to_lowercase(); + let t = raw.to_lowercase(); let rest = |prefix: &str| t.strip_prefix(prefix).map(|r| r.trim().to_string()); // Explicit commands first, so a search/install query cannot be mistaken for @@ -940,7 +955,7 @@ fn parse_natural_raw(text: &str) -> Option { } if let Some(atom) = rest("install ").or_else(|| rest("add ")) { if !atom.is_empty() { - return Some(SystemAction::InstallPackage { atom }); + return Some(SystemAction::InstallPackage { atom, binary: None }); } } if let Some(atom) = rest("remove ") @@ -1270,7 +1285,10 @@ mod tests { fn accepts_bare_package_names() { assert_eq!( parse_action(r#"{"action":"install_package","atom":"vim"}"#).unwrap(), - SystemAction::InstallPackage { atom: "vim".into() } + SystemAction::InstallPackage { + atom: "vim".into(), + binary: None, + } ); let remove = parse_action(r#"{"action":"remove_package","atom":"app-editors/vim"}"#).unwrap(); @@ -1293,13 +1311,24 @@ mod tests { assert_eq!( parse_natural("install app-editors/vim"), Some(SystemAction::InstallPackage { - atom: "app-editors/vim".into() + atom: "app-editors/vim".into(), + binary: None, }) ); // The friendly, apt-like forms resolve to Portage operations. assert_eq!( parse_natural("install vim"), - Some(SystemAction::InstallPackage { atom: "vim".into() }) + Some(SystemAction::InstallPackage { + atom: "vim".into(), + binary: None, + }) + ); + assert_eq!( + parse_natural("please install vim"), + Some(SystemAction::InstallPackage { + atom: "vim".into(), + binary: None, + }) ); assert_eq!( parse_natural("remove vim"), diff --git a/installer-rs/crates/phoebus-core/src/lib.rs b/installer-rs/crates/phoebus-core/src/lib.rs index c1fde3f..5b30daa 100644 --- a/installer-rs/crates/phoebus-core/src/lib.rs +++ b/installer-rs/crates/phoebus-core/src/lib.rs @@ -16,6 +16,7 @@ pub mod nvidia; pub mod nvidia_devices; pub mod plan; pub mod policy; +pub mod proactive; pub mod rollback; pub mod secret; pub mod selection; @@ -40,6 +41,7 @@ pub use policy::{ append_history, load_history, InstallMethod, PackageDecision, PackageDecisionReason, PackagePolicyEngine, PolicyContext, }; +pub use proactive::{DeferredSchedule, ProactiveAlert, ProactiveCategory, ProactiveState}; pub use secret::{Redactor, SecretString}; pub use selection::{ select, Backend, Candidate, Capability, HardwareFacts, Need, PackageKind, Preferences, diff --git a/installer-rs/crates/phoebus-core/src/proactive.rs b/installer-rs/crates/phoebus-core/src/proactive.rs new file mode 100644 index 0000000..8f84b46 --- /dev/null +++ b/installer-rs/crates/phoebus-core/src/proactive.rs @@ -0,0 +1,119 @@ +//! Quiet proactive assistance types and models. +//! +//! Phoebus detects a bounded set of deterministic system events: +//! - Updates ready for review +//! - Repeated service failures +//! - Low storage (< 5 GiB free) +//! - Failed/interrupted installations +//! - Required reboots +//! +//! All proactive events are deduplicated, snoozable, and can be disabled. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProactiveCategory { + UpdatesReady, + ServiceFailure, + LowStorage, + FailedInstallation, + RebootRequired, +} + +impl ProactiveCategory { + pub fn as_str(self) -> &'static str { + match self { + ProactiveCategory::UpdatesReady => "updates_ready", + ProactiveCategory::ServiceFailure => "service_failure", + ProactiveCategory::LowStorage => "low_storage", + ProactiveCategory::FailedInstallation => "failed_installation", + ProactiveCategory::RebootRequired => "reboot_required", + } + } +} + +/// A single bounded proactive alert. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProactiveAlert { + pub id: String, + pub category: ProactiveCategory, + pub title: String, + pub message: String, + pub severity: String, // "info", "warning", "critical" + pub actionable: bool, + pub suggested_phrase: Option, + pub created_unix: u64, + pub fingerprint: String, +} + +/// A deferred request (e.g. "update when I finish working"). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeferredSchedule { + pub id: String, + pub instruction: String, + pub conditions: String, + pub scheduled_unix: u64, + pub approval_digest: String, +} + +/// Persistent state for proactive assistance. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ProactiveState { + pub enabled: bool, + pub snoozed_until_unix: u64, + pub dismissed_fingerprints: Vec, + pub last_checked_unix: u64, + pub deferred_schedule: Option, +} + +impl Default for ProactiveState { + fn default() -> Self { + Self { + enabled: true, + snoozed_until_unix: 0, + dismissed_fingerprints: Vec::new(), + last_checked_unix: 0, + deferred_schedule: None, + } + } +} + +impl ProactiveState { + pub fn is_active(&self, now_unix: u64) -> bool { + self.enabled && now_unix >= self.snoozed_until_unix + } + + pub fn is_dismissed(&self, fingerprint: &str) -> bool { + self.dismissed_fingerprints.iter().any(|f| f == fingerprint) + } + + pub fn dismiss(&mut self, fingerprint: String) { + if !self.is_dismissed(&fingerprint) { + self.dismissed_fingerprints.push(fingerprint); + } + } + + pub fn snooze(&mut self, duration_seconds: u64, now_unix: u64) { + self.snoozed_until_unix = now_unix.saturating_add(duration_seconds); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn proactive_state_snooze_and_dismiss() { + let mut state = ProactiveState::default(); + assert!(state.is_active(100)); + state.snooze(300, 100); + assert!(!state.is_active(200)); + assert!(state.is_active(401)); + + state.dismiss("fp1".into()); + assert!(state.is_dismissed("fp1")); + assert!(!state.is_dismissed("fp2")); + } +} diff --git a/installer-rs/crates/phoebus-core/src/selection.rs b/installer-rs/crates/phoebus-core/src/selection.rs index ebe3b23..b520b4c 100644 --- a/installer-rs/crates/phoebus-core/src/selection.rs +++ b/installer-rs/crates/phoebus-core/src/selection.rs @@ -246,6 +246,46 @@ impl HardwareFacts { } } +/// Preference profile guiding package selection tradeoffs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PreferenceProfile { + #[default] + Balanced, + FastInstallation, + NativeIntegration, + ApplicationIsolation, +} + +impl PreferenceProfile { + pub fn as_str(self) -> &'static str { + match self { + PreferenceProfile::Balanced => "balanced", + PreferenceProfile::FastInstallation => "fast-installation", + PreferenceProfile::NativeIntegration => "native-integration", + PreferenceProfile::ApplicationIsolation => "application-isolation", + } + } + + pub fn parse(val: &str) -> Option { + match val.trim().to_ascii_lowercase().as_str() { + "balanced" => Some(PreferenceProfile::Balanced), + "fast" | "fast-installation" | "fast_installation" | "speed" => { + Some(PreferenceProfile::FastInstallation) + } + "native" | "native-integration" | "native_integration" | "portage" => { + Some(PreferenceProfile::NativeIntegration) + } + "isolated" + | "isolation" + | "application-isolation" + | "application_isolation" + | "sandbox" => Some(PreferenceProfile::ApplicationIsolation), + _ => None, + } + } +} + /// Global and per-application preferences. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] @@ -258,6 +298,14 @@ pub struct Preferences { pub allow_proprietary: bool, /// Favour source over binaries (the `source_first` install policy). pub prefer_source: bool, + /// High-level preference profile (fast install vs native integration vs application isolation). + pub profile: PreferenceProfile, + /// Project-specific tool versions (project path -> tool name -> pinned version). + pub project_environments: BTreeMap>, + /// Keep an already installed application on its existing source. + pub keep_existing_source: bool, + /// Inferred suggestions tracked separately before user confirmation. + pub inferred_preferences: BTreeMap, } impl Default for Preferences { @@ -267,6 +315,10 @@ impl Default for Preferences { per_app: BTreeMap::new(), allow_proprietary: true, prefer_source: false, + profile: PreferenceProfile::Balanced, + project_environments: BTreeMap::new(), + keep_existing_source: true, + inferred_preferences: BTreeMap::new(), } } } @@ -793,6 +845,40 @@ fn score( if prefs.default == Some(c.backend) { s += 12; } + // High-level preference profile adjustments. + match prefs.profile { + PreferenceProfile::Balanced => {} + PreferenceProfile::FastInstallation => { + if c.backend == Backend::PortageBinary + || c.backend == Backend::Flatpak + || c.backend == Backend::Snap + { + s += 20; + why.push(format!( + "preference profile favours fast installation ({})", + c.backend.as_str() + )); + } else if c.backend == Backend::PortageSource { + s -= 20; + } + } + PreferenceProfile::NativeIntegration => { + if c.backend.is_portage() { + s += 20; + why.push("preference profile favours native Portage integration".into()); + } else { + s -= 15; + } + } + PreferenceProfile::ApplicationIsolation => { + if c.backend.is_sandboxed() { + s += 25; + why.push("preference profile favours sandboxed application isolation".into()); + } else if need.gui { + s -= 15; + } + } + } // Update reliability. s += match c.update_reliability { UpdateReliability::Automatic => 6, diff --git a/installer-rs/crates/phoebus-core/src/system.rs b/installer-rs/crates/phoebus-core/src/system.rs index b0ecf52..a78476f 100644 --- a/installer-rs/crates/phoebus-core/src/system.rs +++ b/installer-rs/crates/phoebus-core/src/system.rs @@ -867,22 +867,38 @@ Requires=graphical-session.target After=graphical-session.target "#; -/// The `phoebus-assistant` launcher: opens a terminal for `sys ask`, which -/// proposes typed actions and requires explicit approval. It never grants the -/// model privilege. +/// The `phoebus-assistant` launcher: launches the Quickshell desktop assistant +/// GUI if available, or falls back to a terminal for `sys ask`. pub const PHOEBUS_ASSISTANT_SCRIPT: &str = r#"#!/bin/bash -# Open the Phoebus assistant in a terminal. `sys ask` uses the same typed-action -# broker and approval boundary as the rest of the system. +# Open the Phoebus assistant. If graphical environment and quickshell are available, +# launch the desktop assistant GUI. Otherwise fall back to a terminal with `sys ask`. set -u +if [ -n "${WAYLAND_DISPLAY:-}" ] || [ -n "${DISPLAY:-}" ]; then + if command -v quickshell >/dev/null 2>&1 \ + && [ -f /etc/xdg/quickshell/phoebus-assistant/shell.qml ]; then + exec quickshell --no-duplicate -c phoebus-assistant + fi +fi if command -v kitty >/dev/null 2>&1; then exec kitty --title "Phoebus Assistant" -e bash -lc \ 'read -rp "Phoebus assistant request: " r; sudo sys ask "$r"; \ echo; read -rp "Press Enter to close"' fi -echo "phoebus-assistant: kitty is required for the assistant launcher" >&2 +echo "phoebus-assistant: neither quickshell nor kitty is available" >&2 exit 1 "#; +pub const PHOEBUS_ASSISTANT_DESKTOP_ENTRY: &str = r#"[Desktop Entry] +Name=Phoebus Assistant +Comment=AI-first system administration and assistance +Exec=/usr/local/bin/phoebus-assistant +Icon=system-help +Terminal=false +Type=Application +Categories=System;Settings; +Keywords=system;admin;assistant;ai;sys;install;update; +"#; + /// A Wayland session entry for `/usr/share/wayland-sessions`. pub fn wayland_session_entry(profile: DesktopProfile) -> Option<(&'static str, String)> { match profile { diff --git a/installer-rs/crates/phoebus-core/src/update.rs b/installer-rs/crates/phoebus-core/src/update.rs index 2b93876..cec69df 100644 --- a/installer-rs/crates/phoebus-core/src/update.rs +++ b/installer-rs/crates/phoebus-core/src/update.rs @@ -80,6 +80,87 @@ pub fn build_args() -> Vec<&'static str> { ] } +use crate::selection::Backend; + +/// One package update item. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PackageUpdateItem { + pub name: String, + pub current_version: Option, + pub new_version: String, + pub source: String, +} + +/// Update overview for a specific source / lane. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SourceUpdateOverview { + pub backend: Backend, + pub updates: Vec, + pub supported: bool, + pub note: String, +} + +/// Unified multi-source update overview. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct UnifiedUpdateOverview { + pub sources: Vec, + pub reboot_required: bool, + pub reboot_reason: Option, +} + +impl UnifiedUpdateOverview { + pub fn total_updates(&self) -> usize { + self.sources.iter().map(|s| s.updates.len()).sum() + } + + pub fn updates_for(&self, backend: Backend) -> usize { + self.sources + .iter() + .find(|s| s.backend == backend) + .map(|s| s.updates.len()) + .unwrap_or(0) + } + + pub fn render(&self) -> String { + let mut out = String::new(); + out.push_str("Unified Update Overview:\n"); + let total_updates = self.total_updates(); + if total_updates == 0 { + out.push_str(" All supported package sources are up to date.\n"); + } + for src in &self.sources { + out.push_str(&format!(" [{}] - ", src.backend.as_str())); + if !src.supported { + out.push_str(&format!("unsupported: {}\n", src.note)); + } else if src.updates.is_empty() { + out.push_str(&format!("up to date ({})\n", src.note)); + } else { + out.push_str(&format!( + "{} update(s) available ({}):\n", + src.updates.len(), + src.note + )); + for item in &src.updates { + let prev = item.current_version.as_deref().unwrap_or("none"); + out.push_str(&format!( + " - {} ({} -> {})\n", + item.name, prev, item.new_version + )); + } + } + } + if self.reboot_required { + out.push_str("\nReboot is required:\n"); + if let Some(reason) = &self.reboot_reason { + out.push_str(&format!(" {}\n", reason)); + } else { + out.push_str(" Kernel or core system changes require a reboot.\n"); + } + } + out + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/installer-rs/crates/phoebus-executor/src/actions.rs b/installer-rs/crates/phoebus-executor/src/actions.rs index ab86e29..6dda1ee 100644 --- a/installer-rs/crates/phoebus-executor/src/actions.rs +++ b/installer-rs/crates/phoebus-executor/src/actions.rs @@ -60,7 +60,7 @@ pub fn preview(action: &SystemAction) -> String { /// Whether the command acts on the running system (`/`) rather than a mounted /// alternate target. -fn is_host_root(root: &Path) -> bool { +pub(crate) fn is_host_root(root: &Path) -> bool { root == Path::new("/") } @@ -146,12 +146,16 @@ fn systemctl_spec(root: &Path, operation: &str, verb: &str, name: &str) -> Comma /// or `None` when the action is not a Portage transaction. fn pretend_args(action: &SystemAction) -> Option> { match action { - SystemAction::InstallPackage { atom } => Some(vec![ - "--pretend".into(), - "--color=n".into(), - "--".into(), - atom.clone(), - ]), + SystemAction::InstallPackage { atom, binary } => { + let mut args = vec!["--pretend".into(), "--color=n".into()]; + if *binary == Some(true) { + args.push("--getbinpkg=y".into()); + args.push("--usepkg=y".into()); + } + args.push("--".into()); + args.push(atom.clone()); + Some(args) + } SystemAction::RemovePackage { atom } => Some(vec![ "--pretend".into(), "--unmerge".into(), @@ -194,6 +198,25 @@ pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Resul refusing to proceed unreviewed", )); } + if let SystemAction::InstallPackage { + atom, + binary: Some(true), + } = action + { + if plan + .effects + .iter() + .any(|e| e.source == phoebus_core::effects::EffectSource::Source) + { + return Err(ExecError::operation( + "sys", + "binary unavailable", + format!( + "a prebuilt binary package was requested for `{atom}`, but Portage requires source compilation; a revised review is required" + ), + )); + } + } if root.join(snapshot::SNAPSHOT_DIR).is_dir() { plan.recovery_point = Some("a protective snapshot before the change".into()); } @@ -402,17 +425,21 @@ pub fn execute( )?; format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy()) } - SystemAction::InstallPackage { atom } => { + SystemAction::InstallPackage { atom, binary } => { // Portage resolves a bare name (`vim`) or a full atom. - run_in_target( - exec, - root, - "sys", - "install package", - "emerge", - &["--ask=n".into(), "--".into(), atom.clone()], - )?; - format!("installed {atom} (Portage)") + let mut args = vec!["--ask=n".into()]; + if *binary == Some(true) { + args.push("--getbinpkg=y".into()); + args.push("--usepkg=y".into()); + } + args.push("--".into()); + args.push(atom.clone()); + run_in_target(exec, root, "sys", "install package", "emerge", &args)?; + if *binary == Some(true) { + format!("installed binary package {atom} (Portage)") + } else { + format!("installed {atom} (Portage)") + } } SystemAction::RemovePackage { atom } => { run_in_target( @@ -806,11 +833,8 @@ pub fn execute( outcome.note } SystemAction::InspectUpdates => { - let state = crate::update::load_state(root); - format!( - "status: {:?}\nnote: {}\nlast prepared: {}", - state.status, state.note, state.last_prepared_unix - ) + let overview = crate::update::check_unified_updates(exec, root); + overview.render() } SystemAction::History => { let history = snapshot::read_history(root)?; @@ -1195,6 +1219,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB let root = Path::new("/mnt/phoebus-target"); let action = SystemAction::InstallPackage { atom: "app-editors/vim".into(), + binary: None, }; let plan = resolve_effects(&exec, &action, root).unwrap(); assert!(!plan.effects.is_empty()); @@ -1216,6 +1241,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB let exec = make_exec(runner.clone()); let action = SystemAction::InstallPackage { atom: "--color=n".into(), + binary: None, }; // The read path refuses too. assert!(resolve_effects(&exec, &action, Path::new("/")).is_err()); @@ -1231,6 +1257,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB let exec = make_exec(runner.clone()); let action = SystemAction::InstallPackage { atom: "app-editors/vim".into(), + binary: None, }; let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err(); assert!(err.to_string().contains("could not establish"), "got {err}"); @@ -1246,6 +1273,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB let exec = make_exec(runner.clone()); let action = SystemAction::InstallPackage { atom: "app-editors/vim".into(), + binary: None, }; let plan = resolve_effects(&exec, &action, Path::new("/")).unwrap(); assert!(plan.effects.is_empty()); @@ -1260,6 +1288,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB let approved = phoebus_core::effects::parse_emerge_pretend(PRETEND_VIM); let action = SystemAction::InstallPackage { atom: "net-misc/wget".into(), + binary: None, }; let err = execute_checked( &exec, @@ -1287,6 +1316,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB ( SystemAction::InstallPackage { atom: "app-editors/vim".into(), + binary: None, }, ResolvedPlan::default(), ), diff --git a/installer-rs/crates/phoebus-executor/src/chooser.rs b/installer-rs/crates/phoebus-executor/src/chooser.rs index 8e5c507..a16e3f8 100644 --- a/installer-rs/crates/phoebus-executor/src/chooser.rs +++ b/installer-rs/crates/phoebus-executor/src/chooser.rs @@ -233,7 +233,29 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec { + let out = res.stdout_lossy(); + out.contains("[binary") + || out.contains("[binpkg") + || parse_pretend_version(&out).is_some() + } + _ => false, + }; + let mut bin_c = portage_candidate(&atom, true, version.as_deref(), &facts); + if !bin_available { + bin_c.available = false; + bin_c.notes.push( + "no matching prebuilt binary found on the binhost; source build required" + .into(), + ); + } + out.push(bin_c); } } _ => { @@ -255,6 +277,12 @@ pub fn resolve_candidates(exec: &Exec, root: &Path, need: &Need) -> Vec { + let out = res.stdout_lossy(); + out.contains("[binary") + || out.contains("[binpkg") + || parse_pretend_version(&out).is_some() + } + _ => false, + }; + if bin_available { + candidates.push(portage_candidate( + &atom, + true, + version.as_deref(), + &hardware_facts(exec, root), + )); + } + } else { + candidates.push(portage_candidate( + &atom, + false, + version.as_deref(), + &hardware_facts(exec, root), + )); + } } } } Backend::Nix => { - if crate::nix::installed(root) && phoebus_core::action::valid_nix_attribute(application) + if crate::nix::installed(root) + && phoebus_core::action::valid_nix_attribute(application) + && crate::nix::verify_attribute(exec, root, application) { let mut c = Candidate::new(Backend::Nix, application, "nixpkgs (pinned)"); c.verified = true; c.update_reliability = UpdateReliability::Automatic; + c.notes.push("Nix provides a pinned development environment, not a permanent global installation".into()); candidates.push(c); } } @@ -831,18 +887,40 @@ pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> Installa &CommandSpec::new("sys", "inspect installed flatpaks", "flatpak").args([ "list", "--app", - "--columns=application,version", + "--columns=application,name,version", ]), ) { if out.success { + let app_lower = application.to_ascii_lowercase(); for line in out.stdout_lossy().lines() { - let mut cols = line.split_whitespace(); - if let (Some(id), Some(version)) = (cols.next(), cols.next()) { - if id == application { + let parts: Vec<&str> = line.split('\t').collect(); + let (id, name, version) = if parts.len() >= 3 { + (parts[0].trim(), parts[1].trim(), parts[2].trim()) + } else { + let ws: Vec<&str> = line.split_whitespace().collect(); + if ws.len() >= 3 { + (ws[0], ws[1], ws[2]) + } else if ws.len() == 2 { + (ws[0], ws[0], ws[1]) + } else { + ("", "", "") + } + }; + if !id.is_empty() { + let id_lower = id.to_ascii_lowercase(); + let name_lower = name.to_ascii_lowercase(); + if id_lower == app_lower + || name_lower == app_lower + || id_lower.ends_with(&format!(".{app_lower}")) + { copies.push(InstalledCopy { backend: Backend::Flatpak.as_str().into(), id: id.to_string(), - version: version.to_string(), + version: if version.is_empty() { + "installed".into() + } else { + version.to_string() + }, }); } } @@ -854,7 +932,7 @@ pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> Installa // Snap. if let Ok(entries) = crate::snap::list(exec) { for entry in entries { - if entry.name == application { + if entry.name.eq_ignore_ascii_case(application) { copies.push(InstalledCopy { backend: Backend::Snap.as_str().into(), id: entry.name, @@ -865,7 +943,17 @@ pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> Installa } // AppImage (managed record). - if let Ok(record) = crate::appimage::info(root, application) { + if let Ok(records) = crate::appimage::list(root) { + for record in records { + if record.name.eq_ignore_ascii_case(application) { + copies.push(InstalledCopy { + backend: Backend::AppImage.as_str().into(), + id: record.name, + version: record.version, + }); + } + } + } else if let Ok(record) = crate::appimage::info(root, application) { copies.push(InstalledCopy { backend: Backend::AppImage.as_str().into(), id: record.name, @@ -874,14 +962,17 @@ pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> Installa } // Portage (VDB). - if let Some(version) = portage_installed_version(root, application) { + if let Some((atom, version)) = portage_installed_atom_and_version(root, application) { copies.push(InstalledCopy { backend: Backend::PortageSource.as_str().into(), - id: application.to_string(), + id: atom, version, }); } + // De-duplicate any multiple matches within the same backend + copies.dedup_by(|a, b| a.backend == b.backend && a.id == b.id); + let duplicate = copies.len() > 1; InstallationInspection { application: application.to_string(), @@ -890,8 +981,8 @@ pub fn installed_copies(exec: &Exec, root: &Path, application: &str) -> Installa } } -/// The installed version of a Portage package from the VDB, if present. -fn portage_installed_version(root: &Path, name: &str) -> Option { +/// The installed version and full atom of a Portage package from the VDB, if present. +fn portage_installed_atom_and_version(root: &Path, name: &str) -> Option<(String, String)> { let vdb = root.join("var/db/pkg"); let (category, package) = match name.split_once('/') { Some((c, p)) => (Some(c.to_string()), p.to_string()), @@ -909,13 +1000,20 @@ fn portage_installed_version(root: &Path, name: &str) -> Option { for pkg in pkgs.flatten() { let dir = pkg.file_name().to_string_lossy().to_string(); if let Some(rest) = dir.strip_prefix(&format!("{package}-")) { - return Some(rest.to_string()); + let atom = format!("{category_name}/{package}"); + return Some((atom, rest.to_string())); } } } None } +/// The installed version of a Portage package from the VDB, if present. +#[allow(dead_code)] +pub(crate) fn portage_installed_version(root: &Path, name: &str) -> Option { + portage_installed_atom_and_version(root, name).map(|(_, v)| v) +} + /// A plain-text inventory of the available lanes, for `sys choose` with no /// request and for diagnostics. pub fn lanes_report(exec: &Exec, root: &Path) -> String { diff --git a/installer-rs/crates/phoebus-executor/src/desktop.rs b/installer-rs/crates/phoebus-executor/src/desktop.rs index 9744b33..04507d9 100644 --- a/installer-rs/crates/phoebus-executor/src/desktop.rs +++ b/installer-rs/crates/phoebus-executor/src/desktop.rs @@ -64,6 +64,10 @@ pub fn write_session_script(exec: &Exec, config: &InstallConfig) -> Result<()> { "usr/local/bin/phoebus-assistant", sysgen::PHOEBUS_ASSISTANT_SCRIPT, )?; + target.write( + "usr/share/applications/phoebus-assistant.desktop", + sysgen::PHOEBUS_ASSISTANT_DESKTOP_ENTRY, + )?; // The "Install Phoebus OS" entry point and welcome launcher are live-medium // only: an installed system has no business offering to reinstall itself. diff --git a/installer-rs/crates/phoebus-executor/src/install.rs b/installer-rs/crates/phoebus-executor/src/install.rs index 08cd9f2..dbfc0f6 100644 --- a/installer-rs/crates/phoebus-executor/src/install.rs +++ b/installer-rs/crates/phoebus-executor/src/install.rs @@ -208,6 +208,7 @@ pub fn action_for(_exec: &Exec, root: &Path, candidate: &Candidate) -> Result { Ok(SystemAction::InstallPackage { atom: candidate.id.clone(), + binary: Some(candidate.backend == Backend::PortageBinary), }) } Backend::Flatpak => Ok(SystemAction::FlatpakInstall { @@ -387,6 +388,25 @@ pub fn validate_proposal( ) -> std::result::Result { proposal.validate_structural()?; + if let Some(expected) = request.backend { + if proposal.backend != expected { + return Err(format!( + "installation is constrained to {}, but the proposal selected {}", + expected.as_str(), + proposal.backend.as_str() + )); + } + } + + if request.kind == Some(phoebus_core::selection::PackageKind::BaseSystem) + && !proposal.backend.is_portage() + { + return Err( + "base system components (kernel, drivers, systemd, boot) must be installed through Portage" + .into(), + ); + } + // The proposal may reference the application by a friendly name; resolve // both the general candidate set and the specific backend. let need = request.need(); diff --git a/installer-rs/crates/phoebus-executor/src/lib.rs b/installer-rs/crates/phoebus-executor/src/lib.rs index c30ae93..79b6bdc 100644 --- a/installer-rs/crates/phoebus-executor/src/lib.rs +++ b/installer-rs/crates/phoebus-executor/src/lib.rs @@ -26,6 +26,7 @@ pub mod opencode; pub mod opencode_client; pub mod opencode_server; pub mod portage; +pub mod proactive; pub mod probe; pub mod rollback; pub mod sandbox; diff --git a/installer-rs/crates/phoebus-executor/src/nix.rs b/installer-rs/crates/phoebus-executor/src/nix.rs index 729b9f5..5fbfe19 100644 --- a/installer-rs/crates/phoebus-executor/src/nix.rs +++ b/installer-rs/crates/phoebus-executor/src/nix.rs @@ -291,6 +291,47 @@ pub fn valid_nix_attribute(value: &str) -> bool { phoebus_core::action::valid_nix_attribute(value) } +/// Verify whether an attribute actually exists in nixpkgs. +/// +/// A syntactically valid attribute name is not proof that the package exists. +/// Runs a read-only metadata probe against Nix in the target. +pub fn verify_attribute(exec: &Exec, root: &Path, attribute: &str) -> bool { + if !valid_nix_attribute(attribute) { + return false; + } + if !installed(root) { + return false; + } + if exec.dry_run { + return true; + } + let binary = "/nix/var/nix/profiles/default/bin/nix"; + let res = if crate::actions::is_host_root(root) { + exec.runner.execute( + &CommandSpec::new("sys", "verify nix attribute", binary).args([ + "eval", + "--raw", + &format!("nixpkgs#{attribute}.name"), + ]), + ) + } else { + exec.runner.execute( + &CommandSpec::new("sys", "verify nix attribute", "chroot") + .arg(root.to_string_lossy().to_string()) + .args([ + binary, + "eval", + "--raw", + &format!("nixpkgs#{attribute}.name"), + ]), + ) + }; + match res { + Ok(out) => out.success && !out.stdout_lossy().trim().is_empty(), + Err(_) => false, + } +} + fn write_file(root: &Path, rel: &str, contents: &str) -> Result<()> { let path = target_path(root, rel); if let Some(parent) = path.parent() { diff --git a/installer-rs/crates/phoebus-executor/src/proactive.rs b/installer-rs/crates/phoebus-executor/src/proactive.rs new file mode 100644 index 0000000..369daaa --- /dev/null +++ b/installer-rs/crates/phoebus-executor/src/proactive.rs @@ -0,0 +1,303 @@ +//! Quiet proactive assistance execution and system checks. +//! +//! Deterministically probes: +//! - Updates ready for review +//! - Repeated service failures +//! - Low storage (< 5 GiB) +//! - Failed installations +//! - Required reboots +//! +//! All alerts are deduplicated, snoozable, and can be disabled. + +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use phoebus_core::proactive::{ + DeferredSchedule, ProactiveAlert, ProactiveCategory, ProactiveState, +}; + +use crate::command::CommandSpec; +use crate::error::{ExecError, Result}; +use crate::exec::Exec; +use crate::transaction; +use crate::update::check_unified_updates; + +pub fn state_path(root: &Path) -> PathBuf { + root.join("var/lib/phoebus/proactive-state.toml") +} + +pub fn load_state(root: &Path) -> ProactiveState { + let path = state_path(root); + if !path.exists() { + return ProactiveState::default(); + } + std::fs::read_to_string(&path) + .ok() + .and_then(|t| toml::from_str(&t).ok()) + .unwrap_or_default() +} + +pub fn save_state(exec: &Exec, root: &Path, state: &ProactiveState) -> Result<()> { + let path = state_path(root); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?; + } + let text = toml::to_string_pretty(state) + .map_err(|e| ExecError::operation("proactive", "serialize state", e.to_string()))?; + std::fs::write(&path, text).map_err(|e| ExecError::io(path.clone(), e))?; + exec.logger + .info(format!("proactive state -> {}", path.display())); + Ok(()) +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Run deterministic checks against the system. Returns all currently detected alerts. +pub fn check_system(exec: &Exec, root: &Path) -> Vec { + let now = now_unix(); + let mut alerts = Vec::new(); + + // 1. Required reboot check + if root.join("run/reboot-required").exists() + || root.join("var/run/reboot-required").exists() + || Path::new("/run/reboot-required").exists() + { + alerts.push(ProactiveAlert { + id: format!("reboot-{}", now), + category: ProactiveCategory::RebootRequired, + title: "System reboot required".into(), + message: + "A kernel or critical component was updated and requires a restart to take effect." + .into(), + severity: "info".into(), + actionable: false, + suggested_phrase: Some("Reboot system".into()), + created_unix: now, + fingerprint: "reboot_required".into(), + }); + } + + // 2. Low storage check (< 5 GiB free on root partition) + let df_cmd = + CommandSpec::new("proactive", "storage", "df").args(["-Pk", root.to_str().unwrap_or("/")]); + if let Ok(out) = exec.run(df_cmd) { + if out.success { + let out_str = String::from_utf8_lossy(&out.stdout); + for line in out_str.lines().skip(1) { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() >= 4 { + if let Ok(avail_kib) = parts[3].parse::() { + const FIVE_GIB_KIB: u64 = 5 * 1024 * 1024; + if avail_kib < FIVE_GIB_KIB { + let avail_gib = (avail_kib as f64) / (1024.0 * 1024.0); + alerts.push(ProactiveAlert { + id: format!("storage-{}", now), + category: ProactiveCategory::LowStorage, + title: "Low disk storage".into(), + message: format!("Less than 5 GiB remaining on root filesystem ({:.1} GiB available).", avail_gib), + severity: "warning".into(), + actionable: true, + suggested_phrase: Some("Clean up system package caches".into()), + created_unix: now, + fingerprint: "low_storage_root".into(), + }); + break; + } + } + } + } + } + } + + // 3. Failed transactions check + if let Ok(tx_log) = transaction::read(root) { + for record in tx_log.records.iter().rev().take(5) { + let is_failure = record.result.starts_with("failed") + || record.result == "interrupted" + || record + .outcomes + .iter() + .any(|o| o.status == phoebus_core::transaction::ActionStatus::Failed); + if is_failure { + alerts.push(ProactiveAlert { + id: format!("failed-tx-{}", record.id), + category: ProactiveCategory::FailedInstallation, + title: format!("Operation failed: {}", record.summary), + message: format!( + "Transaction #{} ({}) did not complete successfully: {}.", + record.id, record.summary, record.result + ), + severity: "warning".into(), + actionable: true, + suggested_phrase: Some("sys undo --legacy".into()), + created_unix: record.created_unix, + fingerprint: format!("failed_tx:{}", record.id), + }); + break; // Only report the most recent failed transaction + } + } + } + + // 4. Failed systemd services check + let systemctl_cmd = CommandSpec::new("proactive", "services", "systemctl").args([ + "--failed", + "--no-legend", + "--plain", + ]); + if let Ok(out) = exec.run(systemctl_cmd) { + if out.success { + let out_str = String::from_utf8_lossy(&out.stdout); + for line in out_str.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if !parts.is_empty() { + let unit = parts[0]; + if unit.ends_with(".service") { + alerts.push(ProactiveAlert { + id: format!("svc-{}", unit), + category: ProactiveCategory::ServiceFailure, + title: format!("Service failed: {}", unit), + message: format!( + "System service '{}' has failed and is not running.", + unit + ), + severity: "warning".into(), + actionable: true, + suggested_phrase: Some(format!("Why is {} failing?", unit)), + created_unix: now, + fingerprint: format!("service_failure:{}", unit), + }); + } + } + } + } + } + + // 5. Updates ready for review check + let overview = check_unified_updates(exec, root); + if overview.total_updates() > 0 { + alerts.push(ProactiveAlert { + id: format!("updates-{}", now), + category: ProactiveCategory::UpdatesReady, + title: format!("{} updates ready for review", overview.total_updates()), + message: format!( + "Updates available across package sources: {} Portage, {} Flatpak, {} Snap.", + overview.updates_for(phoebus_core::selection::Backend::PortageBinary) + + overview.updates_for(phoebus_core::selection::Backend::PortageSource), + overview.updates_for(phoebus_core::selection::Backend::Flatpak), + overview.updates_for(phoebus_core::selection::Backend::Snap), + ), + severity: "info".into(), + actionable: true, + suggested_phrase: Some("Show me what needs updating".into()), + created_unix: now, + fingerprint: format!("updates_ready:{}", overview.total_updates()), + }); + } + + alerts +} + +/// Retrieve only active, non-dismissed alerts according to persisted state. +pub fn active_alerts(exec: &Exec, root: &Path) -> (Vec, ProactiveState) { + let now = now_unix(); + let mut state = load_state(root); + state.last_checked_unix = now; + let _ = save_state(exec, root, &state); + + if !state.is_active(now) { + return (Vec::new(), state); + } + + let all = check_system(exec, root); + let filtered = all + .into_iter() + .filter(|a| !state.is_dismissed(&a.fingerprint)) + .collect(); + + (filtered, state) +} + +pub fn snooze(exec: &Exec, root: &Path, duration_seconds: u64) -> Result<()> { + let mut state = load_state(root); + state.snooze(duration_seconds, now_unix()); + save_state(exec, root, &state) +} + +pub fn dismiss(exec: &Exec, root: &Path, fingerprint: &str) -> Result<()> { + let mut state = load_state(root); + state.dismiss(fingerprint.to_string()); + save_state(exec, root, &state) +} + +pub fn set_enabled(exec: &Exec, root: &Path, enabled: bool) -> Result<()> { + let mut state = load_state(root); + state.enabled = enabled; + save_state(exec, root, &state) +} + +pub fn schedule_deferred(exec: &Exec, root: &Path, schedule: DeferredSchedule) -> Result<()> { + let mut state = load_state(root); + state.deferred_schedule = Some(schedule); + save_state(exec, root, &state) +} + +pub fn cancel_deferred(exec: &Exec, root: &Path) -> Result<()> { + let mut state = load_state(root); + state.deferred_schedule = None; + save_state(exec, root, &state) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::command::RecordingRunner; + use crate::log::Logger; + use phoebus_core::Redactor; + use tempfile::tempdir; + + fn make_exec(runner: RecordingRunner, root: &Path) -> Exec { + let temp = tempdir().unwrap().keep(); + let logger = Logger::open(temp.join("l.log"), Redactor::new(), false); + Exec::new(Box::new(runner), logger, false, root.to_path_buf(), temp) + } + + #[test] + fn test_proactive_state_persistence_and_filtering() { + let temp = tempdir().unwrap(); + let root = temp.path(); + let runner = RecordingRunner::new(); + let exec = make_exec(runner, root); + + let state = load_state(root); + assert!(state.enabled); + assert!(state.dismissed_fingerprints.is_empty()); + + // Test dismiss + dismiss(&exec, root, "reboot_required").unwrap(); + let state2 = load_state(root); + assert!(state2.is_dismissed("reboot_required")); + + // Create reboot required file + let run_dir = root.join("run"); + std::fs::create_dir_all(&run_dir).unwrap(); + std::fs::write(run_dir.join("reboot-required"), "").unwrap(); + + // System check finds reboot alert + let all = check_system(&exec, root); + assert!(all.iter().any(|a| a.fingerprint == "reboot_required")); + + // But active_alerts filters it out because it was dismissed + let (active, _) = active_alerts(&exec, root); + assert!(!active.iter().any(|a| a.fingerprint == "reboot_required")); + + // Test snooze + snooze(&exec, root, 3600).unwrap(); + let state3 = load_state(root); + assert!(!state3.is_active(now_unix())); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/update.rs b/installer-rs/crates/phoebus-executor/src/update.rs index cf673ea..ac07cac 100644 --- a/installer-rs/crates/phoebus-executor/src/update.rs +++ b/installer-rs/crates/phoebus-executor/src/update.rs @@ -160,6 +160,169 @@ fn now_unix() -> u64 { .unwrap_or(0) } +use phoebus_core::selection::Backend; +use phoebus_core::update::{PackageUpdateItem, SourceUpdateOverview, UnifiedUpdateOverview}; + +/// Check updates across all supported package sources (Portage, Flatpak, Snap, AppImage, Nix) +/// and report a unified, truthful overview. +pub fn check_unified_updates(exec: &Exec, root: &Path) -> UnifiedUpdateOverview { + let mut sources = Vec::new(); + + // 1. Portage + let mut portage_items = Vec::new(); + let portage_res = exec.runner.execute( + &crate::command::CommandSpec::new("sys", "check portage updates", "emerge").args([ + "--pretend", + "--update", + "--deep", + "--newuse", + "--color=n", + "@world", + ]), + ); + let mut portage_note = "native OS packages".to_string(); + if let Ok(res) = portage_res { + if res.success { + let plan = phoebus_core::effects::parse_emerge_pretend(&res.stdout_lossy()); + for effect in plan.effects { + if effect.kind == phoebus_core::effects::EffectKind::Upgrade + || effect.kind == phoebus_core::effects::EffectKind::New + { + portage_items.push(PackageUpdateItem { + name: effect.target.clone(), + current_version: effect.previous.clone(), + new_version: effect.target, + source: "Portage @world".into(), + }); + } + } + } else { + portage_note = "emerge check failed or offline".into(); + } + } + sources.push(SourceUpdateOverview { + backend: Backend::PortageSource, + updates: portage_items, + supported: true, + note: portage_note, + }); + + // 2. Flatpak + let mut flatpak_items = Vec::new(); + let flatpak_supported = crate::exec::find_in_path("flatpak").is_some(); + let mut flatpak_note = "sandboxed desktop applications".to_string(); + if flatpak_supported { + let fp_res = + exec.runner.execute( + &crate::command::CommandSpec::new("sys", "check flatpak updates", "flatpak") + .args(["remote-ls", "--updates", "--columns=application,version"]), + ); + if let Ok(res) = fp_res { + if res.success { + for line in res.stdout_lossy().lines() { + let mut parts = line.split_whitespace(); + if let (Some(id), Some(ver)) = (parts.next(), parts.next()) { + flatpak_items.push(PackageUpdateItem { + name: id.to_string(), + current_version: None, + new_version: ver.to_string(), + source: "flathub".into(), + }); + } + } + } else { + flatpak_note = "flatpak remote check failed or offline".into(); + } + } + } + sources.push(SourceUpdateOverview { + backend: Backend::Flatpak, + updates: flatpak_items, + supported: flatpak_supported, + note: if flatpak_supported { + flatpak_note + } else { + "flatpak is not installed".into() + }, + }); + + // 3. Snap + let mut snap_items = Vec::new(); + let snap_status = crate::snap::status(exec); + let snap_supported = matches!(snap_status, Ok(ref s) if s.usable()); + let snap_note = "snapd automatic refresh lane".to_string(); + if snap_supported { + let snap_res = exec.runner.execute( + &crate::command::CommandSpec::new("sys", "check snap updates", "snap") + .args(["refresh", "--list"]), + ); + if let Ok(res) = snap_res { + if res.success { + for line in res.stdout_lossy().lines().skip(1) { + let mut parts = line.split_whitespace(); + if let (Some(name), Some(ver)) = (parts.next(), parts.next()) { + snap_items.push(PackageUpdateItem { + name: name.to_string(), + current_version: None, + new_version: ver.to_string(), + source: "Snap Store".into(), + }); + } + } + } + } + } + sources.push(SourceUpdateOverview { + backend: Backend::Snap, + updates: snap_items, + supported: snap_supported, + note: if snap_supported { + snap_note + } else { + "snapd is not installed or active".into() + }, + }); + + // 4. AppImage + let appimages = crate::appimage::list(root).unwrap_or_default(); + sources.push(SourceUpdateOverview { + backend: Backend::AppImage, + updates: Vec::new(), + supported: false, + note: format!( + "{} managed AppImage(s); automatic repository updates are not supported by the format (manual update required)", + appimages.len() + ), + }); + + // 5. Nix + let nix_installed = crate::nix::installed(root); + sources.push(SourceUpdateOverview { + backend: Backend::Nix, + updates: Vec::new(), + supported: nix_installed, + note: if nix_installed { + "Nix dev packages are declarative/pinned; updates are managed per-project or via profile updates".into() + } else { + "Nix is not installed".into() + }, + }); + + // Reboot check: check /var/run/reboot-required + let reboot_required = root.join("var/run/reboot-required").exists(); + let reboot_reason = if reboot_required { + Some("Kernel or core system changes require a reboot (/var/run/reboot-required)".into()) + } else { + None + }; + + UnifiedUpdateOverview { + sources, + reboot_required, + reboot_reason, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs new file mode 100644 index 0000000..6559f05 --- /dev/null +++ b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs @@ -0,0 +1,718 @@ +//! JSON-RPC assistant bridge for the Phoebus desktop assistant. +//! +//! Exposes the exact same AI investigation, deterministic resolution, +//! policy checks, authorization boundary, and transaction recording to the +//! desktop GUI as `sys` CLI. + +use std::io::{BufRead, Write}; +use std::path::Path; + +use phoebus_ai::assistant::complete_plan; +use phoebus_ai::provider::{ProviderKind, SystemFacts}; +use phoebus_core::action::{parse_natural, SystemAction}; +use phoebus_core::selection::Backend; +use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; +use phoebus_core::{AiBackend, InstallConfig, Preferences}; +use phoebus_executor::ai::CurlTransport; +use phoebus_executor::auth::{authorize, Confirmation}; +use phoebus_executor::chooser; +use phoebus_executor::install::{self, InstallRequest}; +use phoebus_executor::opencode_client::ExecOpenCodeTransport; +use phoebus_executor::proactive; +use phoebus_executor::probe; +use phoebus_executor::transaction; +use phoebus_executor::update::check_unified_updates; +use phoebus_executor::{actions, Exec, Result as ExecResult}; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +pub const ASSISTANT_PROTOCOL_VERSION: u32 = 1; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BridgeRequest { + pub id: u64, + pub op: String, + #[serde(default)] + pub request: Option, + #[serde(default)] + pub application: Option, + #[serde(default)] + pub backend: Option, + #[serde(default)] + pub phrase: Option, + #[serde(default)] + pub action: Option, + #[serde(default)] + pub actions: Option>, + #[serde(default)] + pub digest: Option, + #[serde(default)] + pub yes: Option, + #[serde(default)] + pub duration_seconds: Option, + #[serde(default)] + pub fingerprint: Option, + #[serde(default)] + pub preferences: Option, + #[serde(default)] + pub snapshot: Option, +} + +#[derive(Debug, Serialize)] +pub struct BridgeResponse { + pub id: u64, + pub ok: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl BridgeResponse { + pub fn ok(id: u64, result: Value) -> Self { + Self { + id, + ok: true, + result: Some(result), + error: None, + } + } + + pub fn err(id: u64, message: impl Into) -> Self { + Self { + id, + ok: false, + result: None, + error: Some(message.into()), + } + } +} + +struct BridgeConfirm { + assume_yes: bool, +} + +impl Confirmation for BridgeConfirm { + fn confirm_erase(&self, _preview: &str) -> ExecResult { + Ok(self.assume_yes) + } + fn confirm_final(&self, _message: &str) -> ExecResult { + Ok(self.assume_yes) + } +} + +fn now_unix() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn load_installed_ai_config(root: &Path) -> Option { + let conf_path = root.join("etc/phoebus/assistant.conf"); + let text = std::fs::read_to_string(&conf_path).ok()?; + toml::from_str(&text).ok() +} + +fn gather_facts(exec: &Exec, root: &Path) -> SystemFacts { + let conf_path = root.join("etc/phoebus/install.toml"); + let config = std::fs::read_to_string(&conf_path) + .ok() + .and_then(|text| InstallConfig::from_toml(&text).ok()) + .unwrap_or_default(); + let hardware = probe::probe_hardware(exec.runner.as_ref()); + let history = phoebus_core::load_history(&root.join("var/lib/phoebus/compile-times.tsv")); + let binhost = root.join("etc/portage/binrepos.conf").exists(); + let mut facts = SystemFacts::from_system(&config, &hardware, &history, binhost, None); + + let hw = chooser::hardware_facts(exec, root); + facts.storage_free_mib = hw.storage_free_mib; + facts.wayland = hw.wayland; + facts.available_backends = hw + .available_backends + .iter() + .map(|b| b.as_str().to_string()) + .collect(); + let prefs = chooser::load_preferences(root); + facts.saved_preferences = prefs + .per_app + .iter() + .map(|(app, b)| (app.clone(), b.as_str().to_string())) + .collect(); + facts.recovery_snapshots = root.join(phoebus_executor::snapshot::SNAPSHOT_DIR).is_dir(); + facts +} + +pub fn handle_request(exec: &Exec, root: &Path, req: BridgeRequest) -> BridgeResponse { + let id = req.id; + match req.op.as_str() { + "handshake" => { + let ai_conf = load_installed_ai_config(root); + let prefs = chooser::load_preferences(root); + let (alerts, _) = proactive::active_alerts(exec, root); + let overview = check_unified_updates(exec, root); + BridgeResponse::ok( + id, + json!({ + "version": phoebus_core::VERSION, + "protocol_version": ASSISTANT_PROTOCOL_VERSION, + "root": root.display().to_string(), + "ai_configured": ai_conf.is_some(), + "ai_backend": ai_conf.as_ref().map(|c| c.backend.as_str()).unwrap_or("direct"), + "preferences": prefs, + "active_alerts_count": alerts.len(), + "reboot_required": overview.reboot_required, + }), + ) + } + "proactive_alerts" => { + let (alerts, state) = proactive::active_alerts(exec, root); + BridgeResponse::ok( + id, + json!({ + "alerts": alerts, + "state": state, + }), + ) + } + "proactive_snooze" => { + let dur = req.duration_seconds.unwrap_or(3600); + match proactive::snooze(exec, root, dur) { + Ok(()) => BridgeResponse::ok(id, json!({ "snoozed_seconds": dur })), + Err(e) => BridgeResponse::err(id, e.to_string()), + } + } + "proactive_dismiss" => { + let fp = req.fingerprint.unwrap_or_default(); + match proactive::dismiss(exec, root, &fp) { + Ok(()) => BridgeResponse::ok(id, json!({ "dismissed": fp })), + Err(e) => BridgeResponse::err(id, e.to_string()), + } + } + "updates" => { + let overview = check_unified_updates(exec, root); + BridgeResponse::ok(id, json!(overview)) + } + "get_preferences" => { + let prefs = chooser::load_preferences(root); + BridgeResponse::ok(id, json!(prefs)) + } + "set_preferences" => { + if let Some(prefs) = req.preferences { + match chooser::save_preferences(exec, root, &prefs) { + Ok(()) => BridgeResponse::ok(id, json!({ "saved": true })), + Err(e) => BridgeResponse::err(id, e.to_string()), + } + } else { + BridgeResponse::err(id, "missing preferences payload") + } + } + "history" => match transaction::read(root) { + Ok(log) => BridgeResponse::ok(id, json!(log.records)), + Err(e) => BridgeResponse::err(id, e.to_string()), + }, + "undo" => { + let action = SystemAction::Undo { + snapshot: req.snapshot, + }; + execute_action_helper(exec, root, id, action, req.yes.unwrap_or(false)) + } + "legacy_install" => { + let app = match req.application { + Some(a) => a, + None => return BridgeResponse::err(id, "missing application parameter"), + }; + let backend_enum = match req.backend.as_deref().and_then(Backend::parse) { + Some(b) => b, + None => { + return BridgeResponse::err( + id, + "legacy_install requires an explicit backend (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)", + ) + } + }; + let mut install_req = InstallRequest::new(&app); + install_req.backend = Some(backend_enum); + match install::resolve_explicit(exec, root, &install_req) { + Ok(resolved) => BridgeResponse::ok( + id, + json!({ + "kind": "install", + "application": resolved.request.application, + "backend": resolved.candidate.backend.as_str(), + "source": resolved.source.as_str(), + "recommendation": format!("Install {} from {}.", resolved.request.application, resolved.source.as_str()), + "action": resolved.action, + "digest": resolved.approval_digest(), + "effects": resolved.effects.effects, + "requires_root": resolved.action.is_mutating(), + }), + ), + Err(e) => BridgeResponse::err(id, e.to_string()), + } + } + "legacy_execute" => { + let action = if let Some(val) = req.action { + match serde_json::from_value::(val) { + Ok(a) => a, + Err(e) => return BridgeResponse::err(id, format!("invalid action JSON: {e}")), + } + } else if let Some(phrase) = req.phrase { + match parse_natural(&phrase) { + Some(a) => a, + None => { + return BridgeResponse::err(id, format!("could not parse phrase: {phrase}")) + } + } + } else { + return BridgeResponse::err(id, "missing action or phrase parameter"); + }; + execute_action_helper(exec, root, id, action, req.yes.unwrap_or(false)) + } + "ask" => { + let query = req.request.unwrap_or_default(); + if query.trim().is_empty() { + return BridgeResponse::err(id, "empty request"); + } + + // Check if it's an install request + let constrained_backend = req.backend.as_deref().and_then(Backend::parse); + if let Some(app) = parse_install_phrase(&query) { + let mut install_req = InstallRequest::new(&app); + install_req.backend = constrained_backend; + + if install_req.backend.is_none() { + let need = install_req.need(); + let selection = match chooser::choose(exec, root, &need) { + Ok(s) => s, + Err(e) => { + return BridgeResponse::err( + id, + format!("could not resolve candidate: {e}"), + ) + } + }; + install_req.backend = Some(selection.chosen.backend); + } + + let resolved = match install::resolve_explicit(exec, root, &install_req) { + Ok(r) => r, + Err(e) => { + return BridgeResponse::err(id, format!("could not resolve candidate: {e}")) + } + }; + + let best_cand = &resolved.candidate; + let sandbox_desc = match best_cand.sandbox { + phoebus_core::selection::SandboxLevel::Strong => { + "provides application isolation" + } + phoebus_core::selection::SandboxLevel::Partial => "provides partial isolation", + phoebus_core::selection::SandboxLevel::None => { + "provides direct host integration" + } + }; + let build_desc = if best_cand.build_seconds.unwrap_or(0) < 60 { + "it avoids a lengthy build" + } else { + "it compiles optimized native binaries" + }; + let rec_summary = format!( + "Install {} from {}. Recommended because {} and {}.", + resolved.request.application, + resolved.source.as_str(), + build_desc, + sandbox_desc + ); + + return BridgeResponse::ok( + id, + json!({ + "kind": "install", + "application": resolved.request.application, + "backend": resolved.candidate.backend.as_str(), + "source": resolved.source.as_str(), + "recommendation": rec_summary, + "chosen": resolved.candidate, + "alternatives": resolved.alternatives, + "action": resolved.action, + "digest": resolved.approval_digest(), + "effects": resolved.effects.effects, + "requires_root": resolved.action.is_mutating(), + }), + ); + } + + // General natural language request via connected model + let facts = gather_facts(exec, root); + let conf = load_installed_ai_config(root); + let ai_backend = conf + .as_ref() + .map(|c| c.backend) + .unwrap_or(AiBackend::Direct); + + let plan = match ai_backend { + AiBackend::OpenCode => { + let server = conf + .as_ref() + .map(|c| c.opencode_server.clone()) + .unwrap_or_default(); + let op_provider = conf + .as_ref() + .map(|c| c.opencode_provider.clone()) + .unwrap_or_default(); + let model = conf + .as_ref() + .map(|c| c.opencode_model.clone()) + .unwrap_or_default(); + if server.is_empty() || model.is_empty() { + return BridgeResponse::err( + id, + "OpenCode is not configured. Configure model or use legacy mode.", + ); + } + let transport = ExecOpenCodeTransport::new( + exec, + server.clone(), + op_provider, + model.clone(), + ); + match complete_plan( + ProviderKind::Local, + &server, + &model, + &facts, + &query, + &transport, + ) { + Ok(p) => p, + Err(e) => { + return BridgeResponse::err(id, format!("OpenCode plan failed: {e}")) + } + } + } + AiBackend::Direct => { + let provider = conf + .as_ref() + .and_then(|c| ProviderKind::parse(&c.provider)) + .unwrap_or(ProviderKind::None); + if provider == ProviderKind::None { + return BridgeResponse::err(id, "No AI model is connected. Use legacy mode for deterministic administration."); + } + let endpoint = conf + .as_ref() + .map(|c| c.endpoint.clone()) + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| provider.endpoint().to_string()); + let model = conf.as_ref().map(|c| c.model.clone()).unwrap_or_default(); + let transport = CurlTransport::new(exec, None); + match complete_plan( + provider, + &endpoint, + &model, + &facts, + &query, + &transport.sandboxed(), + ) { + Ok(p) => p, + Err(e) => { + return BridgeResponse::err(id, format!("AI investigation failed: {e}")) + } + } + } + }; + + // Resolve effects + let mut resolved_actions = Vec::new(); + let mut any_mutating = false; + for act in &plan.actions { + let eff = actions::resolve_effects(exec, act, root).ok(); + any_mutating |= act.is_mutating(); + resolved_actions.push(json!({ + "action": act, + "effects": eff.map(|e| e.effects).unwrap_or_default(), + })); + } + + BridgeResponse::ok( + id, + json!({ + "kind": "plan", + "summary": plan.summary, + "actions": resolved_actions, + "requires_root": any_mutating, + }), + ) + } + "execute" => { + let actions_val = match req.actions { + Some(a) => a, + None => return BridgeResponse::err(id, "missing actions array"), + }; + let mut parsed_actions = Vec::new(); + let mut any_mutating = false; + for val in actions_val { + let action: SystemAction = match serde_json::from_value(val) { + Ok(a) => a, + Err(e) => { + return BridgeResponse::err( + id, + format!("invalid action in execution list: {e}"), + ) + } + }; + any_mutating |= action.is_mutating(); + parsed_actions.push(action); + } + + let confirm = BridgeConfirm { + assume_yes: req.yes.unwrap_or(false), + }; + let auth = if any_mutating { + match authorize(&confirm, "Desktop Assistant Plan Execution", "execute") { + Ok(a) => Some(a), + Err(e) => return BridgeResponse::err(id, format!("authorization denied: {e}")), + } + } else { + None + }; + + let mut approved_steps = Vec::new(); + for act in &parsed_actions { + let eff = match actions::resolve_effects(exec, act, root) { + Ok(e) => e, + Err(e) => { + return BridgeResponse::err(id, format!("effect revalidation failed: {e}")) + } + }; + approved_steps.push((act.clone(), eff)); + } + + let run = actions::execute_plan(exec, &approved_steps, auth.as_ref(), root); + let mut attempted: Vec = run.completed.iter().map(|(a, _)| a.clone()).collect(); + if let Some((action, _detail)) = &run.failure { + attempted.push(action.clone()); + } + + let result_str = match &run.failure { + None => "ok".to_string(), + Some((action, detail)) => format!("failed: {action}: {detail}"), + }; + + let record = TransactionRecord { + id: 0, + created_unix: now_unix(), + origin: "assistant-gui".into(), + summary: format!("execute {} action(s)", parsed_actions.len()), + actions: attempted, + result: result_str.clone(), + snapshot: run.snapshot.clone(), + digest: req.digest, + outcomes: run.outcomes, + }; + let _ = transaction::append(exec, root, record); + + if let Some((act, det)) = run.failure { + BridgeResponse::err(id, format!("action failed: {act}: {det}")) + } else { + BridgeResponse::ok( + id, + json!({ + "completed": true, + "snapshot": run.snapshot, + "result": result_str, + }), + ) + } + } + unknown => BridgeResponse::err(id, format!("unknown bridge op: {unknown}")), + } +} + +fn execute_action_helper( + exec: &Exec, + root: &Path, + id: u64, + action: SystemAction, + assume_yes: bool, +) -> BridgeResponse { + let approved = match actions::resolve_effects(exec, &action, root) { + Ok(plan) => Some(plan), + Err(e) => return BridgeResponse::err(id, format!("could not resolve effects: {e}")), + }; + + let confirm = BridgeConfirm { assume_yes }; + let auth = if action.is_mutating() { + match authorize(&confirm, &actions::preview(&action), "execute") { + Ok(a) => Some(a), + Err(e) => return BridgeResponse::err(id, format!("authorization denied: {e}")), + } + } else { + None + }; + + let outcome = + match actions::execute_checked(exec, &action, auth.as_ref(), root, approved.as_ref()) { + Ok(o) => o, + Err(e) => return BridgeResponse::err(id, e.to_string()), + }; + + if action.is_mutating() { + let desc = action.describe(); + let record = TransactionRecord { + id: 0, + created_unix: now_unix(), + origin: "sys-legacy".into(), + summary: desc.clone(), + actions: vec![desc.clone()], + result: "ok".into(), + snapshot: outcome.snapshot.clone(), + digest: approved.as_ref().map(|p| p.digest.clone()), + outcomes: vec![TransactionOutcome::completed(desc)], + }; + let _ = transaction::append(exec, root, record); + } + + BridgeResponse::ok( + id, + json!({ + "output": outcome.output, + "snapshot": outcome.snapshot, + }), + ) +} + +fn parse_install_phrase(text: &str) -> Option { + let mut trimmed = text.trim(); + for prefix in ["please ", "Please "] { + if let Some(rest) = trimmed.strip_prefix(prefix) { + trimmed = rest.trim(); + break; + } + } + let lower = trimmed.to_ascii_lowercase(); + for prefix in ["install ", "add "] { + if lower.starts_with(prefix) { + let app = trimmed[prefix.len()..].trim(); + if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') { + return Some(app.to_string()); + } + } + } + None +} + +/// Run line-delimited JSON-RPC loop on stdio. +pub fn run_stdio(exec: &Exec, root: &Path) -> std::result::Result<(), Box> { + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + let mut stdout_lock = stdout.lock(); + + for line in stdin.lock().lines() { + let line = line?; + if line.trim().is_empty() { + continue; + } + let req: BridgeRequest = match serde_json::from_str(&line) { + Ok(r) => r, + Err(e) => { + let resp = BridgeResponse::err(0, format!("invalid JSON request: {e}")); + writeln!(stdout_lock, "{}", serde_json::to_string(&resp)?)?; + stdout_lock.flush()?; + continue; + } + }; + + let resp = handle_request(exec, root, req); + writeln!(stdout_lock, "{}", serde_json::to_string(&resp)?)?; + stdout_lock.flush()?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use phoebus_core::Redactor; + use phoebus_executor::command::RecordingRunner; + use phoebus_executor::Logger; + use tempfile::tempdir; + + fn make_test_exec(root: &Path) -> Exec { + let temp = tempdir().unwrap().keep(); + let logger = Logger::open(temp.join("test.log"), Redactor::new(), false); + Exec::new( + Box::new(RecordingRunner::new()), + logger, + false, + root.to_path_buf(), + temp, + ) + } + + #[test] + fn test_handshake_and_history() { + let temp = tempdir().unwrap(); + let root = temp.path(); + let exec = make_test_exec(root); + + let req = BridgeRequest { + id: 1, + op: "handshake".into(), + request: None, + application: None, + backend: None, + phrase: None, + action: None, + actions: None, + digest: None, + yes: None, + duration_seconds: None, + fingerprint: None, + preferences: None, + snapshot: None, + }; + + let resp = handle_request(&exec, root, req); + assert!(resp.ok); + assert_eq!(resp.id, 1); + let res = resp.result.unwrap(); + assert_eq!(res["protocol_version"], ASSISTANT_PROTOCOL_VERSION); + + // Test history request + let hist_req = BridgeRequest { + id: 2, + op: "history".into(), + request: None, + application: None, + backend: None, + phrase: None, + action: None, + actions: None, + digest: None, + yes: None, + duration_seconds: None, + fingerprint: None, + preferences: None, + snapshot: None, + }; + let hist_resp = handle_request(&exec, root, hist_req); + assert!(hist_resp.ok); + } + + #[test] + fn test_parse_install_phrase() { + assert_eq!( + parse_install_phrase("install firefox"), + Some("firefox".into()) + ); + assert_eq!( + parse_install_phrase("please install firefox"), + Some("firefox".into()) + ); + assert_eq!(parse_install_phrase("add vlc"), Some("vlc".into())); + assert_eq!(parse_install_phrase("why is audio broken"), None); + } +} diff --git a/installer-rs/crates/phoebus-installer/src/bin/sys.rs b/installer-rs/crates/phoebus-installer/src/bin/sys.rs index 271a8df..be82510 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/sys.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/sys.rs @@ -1,9 +1,10 @@ -//! `sys ` - proposed Phoebus system interface. +//! `sys ` - Phoebus unified system interface. //! -//! The normal path is deterministic: a phrase is parsed into a closed, -//! validated `SystemAction`, shown for approval, and executed by the -//! privileged broker. The AI path emits the same typed schema via -//! `--action-file`; it never receives a shell or the sudo password. +//! Natural language is the default interaction: a connected model investigates +//! the request, recommends a validated plan, and explains it. +//! Deterministic operation without a model is explicitly selected with `--legacy`. +//! All operations execute typed, validated actions through the privileged broker; +//! the model never receives a shell or privilege. use std::io::Write; use std::path::{Path, PathBuf}; @@ -33,14 +34,26 @@ use phoebus_executor::{ ]).multiple(false)) )] struct Cli { - /// Natural-language instruction, e.g. `enable sshd`. + /// Natural-language instruction, e.g. `enable sshd` or `install firefox`. text: Vec, + /// Explicit deterministic administration without contacting a model. + #[arg(long)] + legacy: bool, + + /// Internal broker invocation by Phoebus OS application layer. + #[arg(long)] + broker: bool, + + /// Start the desktop assistant JSON-RPC bridge on stdio. + #[arg(long)] + assistant_bridge: bool, + /// A typed action as JSON, e.g. '{"action":"enable_service","name":"sshd"}'. #[arg(long)] action: Option, - /// Read a typed action from a JSON file (used by the AI path). + /// Read a typed action from a JSON file (used by the AI path or internal broker). #[arg(long)] action_file: Option, @@ -52,27 +65,27 @@ struct Cli { #[arg(long, default_value = "/")] root: PathBuf, - /// Install through Portage only (no model needed). + /// Constrain to Portage (or in --legacy mode, install through Portage). #[arg(long)] portage: bool, - /// Install from Flatpak only (no model needed). + /// Constrain to Flatpak (or in --legacy mode, install from Flatpak). #[arg(long)] flatpak: bool, - /// Install from Nix only (no model needed). + /// Constrain to Nix (or in --legacy mode, install from Nix). #[arg(long)] nix: bool, - /// Install from Snap only (no model needed). + /// Constrain to Snap (or in --legacy mode, install from Snap). #[arg(long)] snap: bool, - /// Install a managed AppImage only (no model needed). + /// Constrain to AppImage (or in --legacy mode, install managed AppImage). #[arg(long)] appimage: bool, - /// Build and install a staged custom ebuild only (no model needed). + /// Constrain to staged custom ebuild (or in --legacy mode, build staged ebuild). #[arg(long)] ebuild: bool, @@ -154,9 +167,6 @@ fn now_unix() -> u64 { .unwrap_or(0) } -/// Append a transaction and make a recording failure visible instead of -/// silently claiming success. The system change (if any) has already happened, -/// so the message says so explicitly. fn record_transaction( exec: &Exec, root: &Path, @@ -203,23 +213,106 @@ fn run() -> std::result::Result<(), Box> { state_dir, ); - // `sys ask ` is the conversational entry point; it proposes the - // same typed actions and executes them through the same broker. + // 1. Assistant Bridge + if cli.assistant_bridge { + return phoebus_installer::assistant_bridge::run_stdio(&exec, &cli.root); + } + + // 2. Audit JSON/action-file entry points + if cli.action.is_some() || cli.action_file.is_some() { + if !cli.legacy && !cli.broker { + return Err( + "typed actions via --action/--action-file require --legacy for deterministic \ + administration or --broker for internal broker invocation" + .into(), + ); + } + let action = if let Some(json) = &cli.action { + parse_action(json)? + } else if let Some(path) = &cli.action_file { + let text = std::fs::read_to_string(path)?; + parse_action(&text)? + } else { + unreachable!(); + }; + return execute_action(&cli, &exec, action); + } + + let backend = backend_flag(&cli); + let full_phrase = cli.text.join(" "); + + // 3. Explicit legacy mode (--legacy) + if cli.legacy { + if let Some(application) = parse_install_text(&full_phrase) { + if let Some(b) = backend { + let mut request = InstallRequest::new(&application); + request.backend = Some(b); + let resolved = install::resolve_explicit(&exec, &cli.root, &request)?; + return execute_resolved(&cli, &exec, resolved); + } else { + eprintln!("sys: legacy install requires an explicit package source flag."); + eprintln!("Specify one of:"); + eprintln!(" sys install {application} --legacy --flatpak"); + eprintln!(" sys install {application} --legacy --portage"); + eprintln!(" sys install {application} --legacy --nix"); + eprintln!(" sys install {application} --legacy --snap"); + eprintln!(" sys install {application} --legacy --appimage"); + eprintln!(" sys install {application} --legacy --ebuild"); + return Err("legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)".into()); + } + } + if backend.is_some() { + return Err( + "--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ + `sys install `" + .into(), + ); + } + if full_phrase.trim().is_empty() { + return Err("usage: sys --legacy".into()); + } + return match parse_natural(&full_phrase) { + Some(action) => execute_action(&cli, &exec, action), + None => { + eprintln!("sys: could not parse `{full_phrase}` in legacy mode."); + eprintln!( + "Legacy mode grammar: sys install --legacy -- | \ + sys history --legacy | sys undo --legacy | sys enable --legacy | \ + sys disable --legacy | sys choose --legacy" + ); + Err("unsupported instruction in legacy mode".into()) + } + }; + } + + // 4. Default AI mode (natural language) + if cli.text.is_empty() { + eprintln!("sys: no instruction provided."); + eprintln!("Natural language administration is the default:"); + eprintln!(" sys install "); + eprintln!(" sys please install "); + eprintln!(" sys ask \"\""); + eprintln!("Or select deterministic legacy administration:"); + eprintln!(" sys install --legacy --"); + eprintln!(" sys history --legacy"); + eprintln!(" sys undo --legacy"); + return Err("missing instruction".into()); + } + + // Conversational `sys ask ` if cli.text.first().map(String::as_str) == Some("ask") { let instruction = cli.text[1..].join(" "); if instruction.trim().is_empty() { return Err("usage: sys ask ".into()); } - return run_ask(&cli, &exec, &instruction); + return run_ask(&cli, &exec, &instruction, backend); } - // `sys install ` is AI-first: a connected model investigates - // and recommends, while an explicit backend flag is deterministic and needs - // no model. Both share `phoebus_executor::install`. - let backend = backend_flag(&cli); - if let Some(application) = parse_install_text(&cli.text.join(" ")) { + // Natural `sys install ` / `sys please install ` + if let Some(application) = parse_install_text(&full_phrase) { return run_install(&cli, &exec, &application, backend); } + if backend.is_some() { return Err( "--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ @@ -228,33 +321,18 @@ fn run() -> std::result::Result<(), Box> { ); } - let action = if let Some(json) = &cli.action { - parse_action(json)? - } else if let Some(path) = &cli.action_file { - let text = std::fs::read_to_string(path)?; - parse_action(&text)? - } else { - let phrase = cli.text.join(" "); - match parse_natural(&phrase) { - Some(a) => a, - None => { - eprintln!("sys: could not parse `{phrase}` deterministically."); - eprintln!( - "Examples: sys enable sshd | sys install vim | sys choose firefox | \ - sys history" - ); - eprintln!("Or ask the assistant: sys ask \"\""); - return Err("unsupported instruction".into()); - } - } - }; + // Other natural language instructions enter the AI workflow by default + run_ask(&cli, &exec, &full_phrase, None) +} +fn execute_action( + cli: &Cli, + exec: &Exec, + action: SystemAction, +) -> std::result::Result<(), Box> { println!("{}", actions::preview(&action)); - // Resolve concrete package effects (additions/upgrades/removals, source vs - // binary, download size) and bind the approval to that exact plan. A - // material change between review and execution aborts. - let approved = match actions::resolve_effects(&exec, &action, &cli.root) { + let approved = match actions::resolve_effects(exec, &action, &cli.root) { Ok(plan) if !plan.effects.is_empty() => { println!("{}", plan.render()); Some(plan) @@ -284,24 +362,19 @@ fn run() -> std::result::Result<(), Box> { None }; - // `actions::execute_checked` re-resolves and compares against the reviewed - // digest, creates a protective snapshot for high-risk actions, and fails - // closed when the snapshots subvolume exists but creation fails. let outcome = - actions::execute_checked(&exec, &action, auth.as_ref(), &cli.root, approved.as_ref())?; + actions::execute_checked(exec, &action, auth.as_ref(), &cli.root, approved.as_ref())?; if let Some(id) = &outcome.snapshot { println!("protective snapshot: {id}"); } println!("{}", outcome.output); - // Ordinary mutating commands are part of the same audited history as - // assistant actions, including their protective snapshot and outcome. if action.is_mutating() { let described = action.describe(); let record = TransactionRecord { id: 0, created_unix: now_unix(), - origin: "sys".into(), + origin: "sys-legacy".into(), summary: described.clone(), actions: vec![described.clone()], result: "ok".into(), @@ -309,7 +382,7 @@ fn run() -> std::result::Result<(), Box> { digest: approved.as_ref().map(|p| p.digest.clone()), outcomes: vec![TransactionOutcome::completed(described)], }; - record_transaction(&exec, &cli.root, record)?; + record_transaction(exec, &cli.root, record)?; } Ok(()) } @@ -337,11 +410,26 @@ fn backend_flag(cli: &Cli) -> Option { } } -/// Parse `install ` / `add `. Option-like operands -/// are left to the deterministic parser so `install --color=n` is still -/// rejected as before. +fn backend_flag_name(backend: Backend) -> &'static str { + match backend { + Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => "portage", + Backend::Flatpak => "flatpak", + Backend::Nix => "nix", + Backend::Snap => "snap", + Backend::AppImage => "appimage", + Backend::CustomEbuild => "ebuild", + } +} + +/// Parse `install ` / `add ` / `please install `. fn parse_install_text(text: &str) -> Option { - let trimmed = text.trim(); + let mut trimmed = text.trim(); + for prefix in ["please ", "Please "] { + if let Some(rest) = trimmed.strip_prefix(prefix) { + trimmed = rest.trim(); + break; + } + } let lower = trimmed.to_ascii_lowercase(); for prefix in ["install ", "add "] { if lower.starts_with(prefix) { @@ -355,8 +443,6 @@ fn parse_install_text(text: &str) -> Option { } /// Load the installed system's configuration instead of assuming defaults. -/// Distinguishes the real target from the development host (the root is the -/// target; nothing here reads the host's own configuration). fn load_installed_config(root: &Path) -> InstallConfig { let path = root.join("etc/phoebus/install.toml"); std::fs::read_to_string(&path) @@ -365,9 +451,6 @@ fn load_installed_config(root: &Path) -> InstallConfig { .unwrap_or_default() } -/// A bounded asker for questions about user intent. Disabled under `--yes` or -/// when stdin is not a terminal: the AI loop is then told to proceed with a -/// conservative assumption. fn install_asker(cli: &Cli) -> Option> { use std::io::IsTerminal; if cli.yes || !std::io::stdin().is_terminal() { @@ -403,13 +486,13 @@ fn print_install_offer(cli: &Cli, exec: &Exec, application: &str) { } eprintln!(); eprintln!("No connected model is available for an unqualified install, so Phoebus will"); - eprintln!("not choose a lane for you. Install explicitly, for example:"); - eprintln!(" sys install {application} --flatpak"); - eprintln!(" sys install {application} --portage"); - eprintln!(" sys install {application} --nix"); - eprintln!(" sys install {application} --snap"); - eprintln!(" sys install {application} --appimage"); - eprintln!(" sys install {application} --ebuild"); + eprintln!("not choose a lane for you. Install explicitly with legacy mode, for example:"); + eprintln!(" sys install {application} --legacy --flatpak"); + eprintln!(" sys install {application} --legacy --portage"); + eprintln!(" sys install {application} --legacy --nix"); + eprintln!(" sys install {application} --legacy --snap"); + eprintln!(" sys install {application} --legacy --appimage"); + eprintln!(" sys install {application} --legacy --ebuild"); } /// `sys install `: the shared installation workflow. @@ -422,14 +505,6 @@ fn run_install( let mut request = InstallRequest::new(application); request.backend = backend; - // An explicit backend is deterministic and works without a model. - if backend.is_some() { - let resolved = install::resolve_explicit(exec, &cli.root, &request)?; - return execute_resolved(cli, exec, resolved); - } - - // Unqualified: the configured model investigates and recommends. A - // provider failure never becomes permission to install through a lane. let conf = load_installed_ai_config(&cli.root); let ai_backend = resolve_backend(cli, conf.as_ref()); let facts = gather_facts(exec); @@ -460,7 +535,16 @@ fn run_install( || opencode_provider.trim().is_empty() || opencode_model.trim().is_empty() { - print_install_offer(cli, exec, application); + if let Some(b) = backend { + eprintln!("sys: OpenCode is not configured for this request."); + eprintln!("Run deterministically without a model using legacy mode:"); + eprintln!( + " sys install {application} --legacy --{}", + backend_flag_name(b) + ); + } else { + print_install_offer(cli, exec, application); + } return Err( "OpenCode needs --opencode-server, --opencode-provider and --opencode-model" .into(), @@ -486,15 +570,36 @@ fn run_install( AiBackend::Direct => { provider = resolve_provider(cli, conf.as_ref()); if provider == ProviderKind::None { - print_install_offer(cli, exec, application); - return Err("no AI provider configured for an unqualified install".into()); + if let Some(b) = backend { + eprintln!("sys: no AI provider is configured for this request."); + eprintln!("Run deterministically without a model using legacy mode:"); + eprintln!( + " sys install {application} --legacy --{}", + backend_flag_name(b) + ); + } else { + print_install_offer(cli, exec, application); + } + return Err("no AI provider configured".into()); } let key = match api_key_file(cli) { Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?), None => None, }; if provider.requires_key() && key.is_none() { - print_install_offer(cli, exec, application); + if let Some(b) = backend { + eprintln!( + "sys: provider `{}` requires --ai-api-key-file (mode 0600)", + provider.as_str() + ); + eprintln!("Run deterministically without a model using legacy mode:"); + eprintln!( + " sys install {application} --legacy --{}", + backend_flag_name(b) + ); + } else { + print_install_offer(cli, exec, application); + } return Err(format!( "provider `{}` requires --ai-api-key-file (mode 0600)", provider.as_str() @@ -512,10 +617,19 @@ fn run_install( } } - eprintln!( - "Investigating `{application}` with {} (bounded, read-only evidence only)...", - provider.as_str() - ); + if let Some(b) = backend { + eprintln!( + "Investigating `{application}` (constrained to {}) with {} (bounded, read-only evidence only)...", + b.as_str(), + provider.as_str() + ); + } else { + eprintln!( + "Investigating `{application}` with {} (bounded, read-only evidence only)...", + provider.as_str() + ); + } + let ai = AiInstall { provider, endpoint, @@ -533,9 +647,18 @@ fn run_install( { Ok(resolved) => resolved, Err(e) => { - // The model failed: offer the deterministic path and stop; do not - // install through any backend. - print_install_offer(cli, exec, application); + // The model failed: offer the actionable legacy alternative and stop; + // do not install through any backend. + if let Some(b) = backend { + eprintln!("sys: the AI investigation did not produce a plan ({e})."); + eprintln!("Run deterministically without a model using legacy mode:"); + eprintln!( + " sys install {application} --legacy --{}", + backend_flag_name(b) + ); + } else { + print_install_offer(cli, exec, application); + } return Err(format!("the AI investigation did not produce a plan: {e}").into()); } }; @@ -586,12 +709,14 @@ fn execute_resolved( resolved.candidate.backend.as_str(), resolved.source.as_str() ); - // Record before mutation: an interrupted run leaves a visible in-progress - // record rather than a missing one. let record = TransactionRecord { id: 0, created_unix: now_unix(), - origin: "sys".into(), + origin: if cli.legacy { + "sys-legacy".into() + } else { + "sys".into() + }, summary: described.clone(), actions: vec![described.clone()], result: "in progress".into(), @@ -661,10 +786,6 @@ fn gather_facts(exec: &Exec) -> SystemFacts { let binhost = exec.root.join("etc/portage/binrepos.conf").exists(); let mut facts = SystemFacts::from_system(&config, &hardware, &history, binhost, None); - // Add bounded, read-only environment facts beyond the static config: - // real free space, Wayland, the lanes that are actually usable, saved - // preferences and recovery capability. These are the same facts the - // deterministic selector uses, so the AI and the resolver agree. let hw = chooser::hardware_facts(exec, &exec.root); facts.storage_free_mib = hw.storage_free_mib; facts.wayland = hw.wayland; @@ -692,7 +813,6 @@ fn load_installed_ai_config(root: &Path) -> Option { toml::from_str(&text).ok() } -/// The AI backend selected on the command line or the environment. fn resolve_backend(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> AiBackend { let raw = cli .ai_backend @@ -703,7 +823,6 @@ fn resolve_backend(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> AiBacken AiBackend::parse(&raw).unwrap_or(AiBackend::Direct) } -/// The provider selected on the command line or the environment. fn resolve_provider(cli: &Cli, conf: Option<&phoebus_core::AiConfig>) -> ProviderKind { let raw = cli .ai_provider @@ -751,19 +870,17 @@ fn api_key_file(cli: &Cli) -> Option { }) } -/// Report the deterministic fallback when no model is available. The system is -/// never unusable without an assistant. fn deterministic_fallback(instruction: &str) { - eprintln!("No model is connected. The deterministic interface still works:"); + eprintln!("No connected model is available. The deterministic legacy interface still works:"); match parse_natural(instruction) { Some(action) => { - eprintln!(" sys {}", action.describe()); - eprintln!("Run it as: sys {}", instruction.trim()); + eprintln!(" sys {} --legacy", action.describe()); + eprintln!("Run it as: sys {} --legacy", instruction.trim()); } None => { eprintln!( - " Examples: sys enable sshd | sys install vim | sys choose firefox | \ - sys history | sys undo" + " Examples: sys enable sshd --legacy | sys install vim --legacy -- | \ + sys history --legacy | sys undo --legacy" ); eprintln!(" A model only makes this easier; it is never required."); } @@ -776,20 +893,19 @@ fn run_ask( cli: &Cli, exec: &Exec, instruction: &str, + backend: Option, ) -> std::result::Result<(), Box> { - // An installation request through `sys ask` uses the same shared workflow - // (AI investigation + deterministic validation) as `sys install`. if let Some(application) = parse_install_text(instruction) { - return run_install(cli, exec, &application, backend_flag(cli)); + return run_install(cli, exec, &application, backend); } let facts = gather_facts(exec); let conf = load_installed_ai_config(&cli.root); - let backend = resolve_backend(cli, conf.as_ref()); + let ai_backend = resolve_backend(cli, conf.as_ref()); let (provider, endpoint, model); let transport: Box; - match backend { + match ai_backend { AiBackend::OpenCode => { let server = cli .opencode_server @@ -823,12 +939,6 @@ fn run_ask( Some(path) => Some(phoebus_executor::ai::load_api_key(path)?), None => None, }; - eprintln!( - "Sending these bounded system facts through the OpenCode server at {} \ - (provider {}, model {}); no passwords, files or home directories:", - server, opencode_provider, opencode_model - ); - eprintln!("{}", facts.render()); provider = ProviderKind::Local; endpoint = server; model = opencode_model; @@ -860,12 +970,6 @@ fn run_ask( ) .into()); } - eprintln!( - "Sending these bounded system facts to {} \ - (no passwords, files or home directories):", - resolved.as_str() - ); - eprintln!("{}", facts.render()); provider = resolved; endpoint = resolve_endpoint(cli, resolved, conf.as_ref()); model = resolve_model(cli, conf.as_ref()); @@ -896,7 +1000,6 @@ fn run_ask( println!("{}", plan.render()); - // Resolve concrete effects and bind approval to the reviewed plan. let mut approved = Vec::new(); let mut mutating = false; for action in &plan.actions { @@ -929,9 +1032,6 @@ fn run_ask( None }; - // The reviewed plans and actions are executed through the shared, - // failure-aware plan runner: it stops at the first failure and records the - // remaining actions as unattempted. let digest = approved .iter() .find(|p| !p.digest.is_empty()) @@ -965,8 +1065,6 @@ fn run_ask( }; record_transaction(exec, &cli.root, record)?; - // A plan that did not fully apply is a failure: nonzero exit, so scripts - // and the GUI cannot mistake it for success. if let Some((action, detail)) = run.failure { return Err(format!("the assistant plan did not complete: {action}: {detail}").into()); } diff --git a/installer-rs/crates/phoebus-installer/src/lib.rs b/installer-rs/crates/phoebus-installer/src/lib.rs index 8fd1f1e..ffdbfd9 100644 --- a/installer-rs/crates/phoebus-installer/src/lib.rs +++ b/installer-rs/crates/phoebus-installer/src/lib.rs @@ -1,6 +1,7 @@ //! Phoebus installer orchestration and CLI support. pub mod ai_guide; +pub mod assistant_bridge; pub mod gui_bridge; pub mod orchestrate; pub mod release; diff --git a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs index a43824a..5b4a0b5 100644 --- a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs +++ b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs @@ -1,9 +1,8 @@ -//! CLI-level regression tests for the `sys` entry paths. +//! CLI-level regression tests for the `sys` entry paths and contracts. //! -//! These exercise the real binary so the deterministic (manual) and JSON paths -//! are proven to fail closed on invalid input and to exit nonzero on failure. -//! They never mutate the system: the invalid cases are refused before any -//! command is built, and the read-only case targets a temporary root. +//! Natural language is the default interaction (calling the AI assistant). +//! Deterministic operation is explicitly selected with `--legacy`. +//! JSON action entry points require `--legacy` or `--broker`. use std::process::Command; @@ -11,25 +10,53 @@ fn sys() -> Command { Command::new(env!("CARGO_BIN_EXE_sys")) } +fn effective_uid_is_root() -> bool { + std::process::Command::new("id") + .arg("-u") + .output() + .ok() + .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "0") + .unwrap_or(false) +} + #[test] -fn natural_option_like_operand_is_rejected() { - // `--` stops clap option parsing, so the operand reaches the parser intact. +fn natural_option_like_operand_is_rejected_in_legacy_mode() { let out = sys() - .args(["--", "install", "--color=n"]) + .args(["--legacy", "--", "install", "--color=n"]) .output() .expect("run sys"); assert!(!out.status.success()); let stderr = String::from_utf8_lossy(&out.stderr); assert!( - stderr.contains("could not parse") || stderr.contains("invalid"), + stderr.contains("could not parse") + || stderr.contains("invalid") + || stderr.contains("legacy"), "stderr: {stderr}" ); } #[test] -fn json_option_like_operand_is_rejected() { +fn json_without_legacy_or_broker_is_rejected() { let out = sys() - .args(["--action", r#"{"action":"install_package","atom":"-C"}"#]) + .args(["--action", r#"{"action":"history"}"#]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("require --legacy") || stderr.contains("--broker"), + "stderr: {stderr}" + ); +} + +#[test] +fn json_option_like_operand_is_rejected_in_legacy_mode() { + let out = sys() + .args([ + "--legacy", + "--action", + r#"{"action":"install_package","atom":"-C"}"#, + ]) .output() .expect("run sys"); assert!(!out.status.success()); @@ -38,12 +65,28 @@ fn json_option_like_operand_is_rejected() { } #[test] -fn read_only_history_succeeds_against_a_temporary_root() { +fn broker_allows_action_execution() { let root = tempfile::tempdir().expect("temp root"); let out = sys() .arg("--root") .arg(root.path()) - .arg("history") + .args(["--broker", "--action", r#"{"action":"history"}"#]) + .output() + .expect("run sys"); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); +} + +#[test] +fn read_only_history_succeeds_deterministically_with_legacy() { + let root = tempfile::tempdir().expect("temp root"); + let out = sys() + .arg("--root") + .arg(root.path()) + .args(["history", "--legacy"]) .output() .expect("run sys"); assert!( @@ -58,6 +101,24 @@ fn read_only_history_succeeds_against_a_temporary_root() { ); } +#[test] +fn history_without_legacy_and_no_model_gives_actionable_legacy_guidance() { + let root = tempfile::tempdir().expect("temp root"); + let out = sys() + .env("PHOEBUS_AI_PROVIDER", "none") + .arg("--root") + .arg(root.path()) + .arg("history") + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("sys history --legacy"), + "expected legacy suggestion in stderr: {stderr}" + ); +} + #[test] fn version_is_reported() { let out = sys().arg("--version").output().expect("run sys"); @@ -72,6 +133,7 @@ fn appimage_and_custom_ebuild_inventories_are_safe_and_empty_on_a_fresh_root() { let out = sys() .arg("--root") .arg(root.path()) + .arg("--legacy") .args(&args) .output() .expect("run sys"); @@ -92,7 +154,11 @@ fn appimage_and_custom_ebuild_inventories_are_safe_and_empty_on_a_fresh_root() { #[test] fn invalid_snap_name_via_json_fails_closed() { let out = sys() - .args(["--action", r#"{"action":"snap_install","name":"Bad Name"}"#]) + .args([ + "--legacy", + "--action", + r#"{"action":"snap_install","name":"Bad Name"}"#, + ]) .output() .expect("run sys"); assert!(!out.status.success()); @@ -103,6 +169,7 @@ fn invalid_snap_name_via_json_fails_closed() { fn invalid_appimage_hash_via_json_fails_closed() { let out = sys() .args([ + "--legacy", "--action", r#"{"action":"appimage_acquire","name":"x","url":"https://e/x","sha256":"00"}"#, ]) @@ -114,25 +181,15 @@ fn invalid_appimage_hash_via_json_fails_closed() { #[test] fn a_mutating_action_without_root_is_refused_before_any_command() { - // This runs as the test user (not root); the mutation must be refused. if effective_uid_is_root() { return; } let root = tempfile::tempdir().expect("temp root"); - let out = sys() - .arg("--root") - .arg(root.path()) - .args(["--action", r#"{"action":"snap_list"}"#]) - .output() - .expect("run sys"); - // snap_list is read-only, so it will instead fail because snapd is absent; - // the point is only that it never mutates. A mutating action is checked - // separately below. - let _ = out; let mutating = sys() .arg("--root") .arg(root.path()) .args([ + "--legacy", "--action", r#"{"action":"set_package_preference","name":"firefox","backend":"flatpak"}"#, ]) @@ -142,15 +199,6 @@ fn a_mutating_action_without_root_is_refused_before_any_command() { assert!(String::from_utf8_lossy(&mutating.stderr).contains("root")); } -fn effective_uid_is_root() -> bool { - std::process::Command::new("id") - .arg("-u") - .output() - .ok() - .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "0") - .unwrap_or(false) -} - #[test] fn conflicting_backend_flags_are_rejected_by_the_cli() { let out = sys() @@ -170,7 +218,7 @@ fn conflicting_backend_flags_are_rejected_by_the_cli() { #[test] fn a_backend_flag_without_an_install_is_refused() { let out = sys() - .args(["--flatpak", "history"]) + .args(["--flatpak", "history", "--legacy"]) .output() .expect("run sys"); assert!(!out.status.success()); @@ -178,10 +226,47 @@ fn a_backend_flag_without_an_install_is_refused() { assert!(stderr.contains("only apply to"), "stderr: {stderr}"); } +#[test] +fn legacy_install_without_source_flag_is_refused_with_choices() { + let root = tempfile::tempdir().expect("temp root"); + let out = sys() + .arg("--root") + .arg(root.path()) + .args(["install", "firefox", "--legacy"]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("requires an explicit package source flag"), + "stderr: {stderr}" + ); + assert!( + stderr.contains("--flatpak") && stderr.contains("--portage"), + "stderr must show explicit options: {stderr}" + ); +} + +#[test] +fn source_flag_without_legacy_enters_ai_workflow_and_suggests_legacy() { + let root = tempfile::tempdir().expect("temp root"); + let out = sys() + .env("PHOEBUS_AI_PROVIDER", "none") + .arg("--root") + .arg(root.path()) + .args(["install", "firefox", "--flatpak"]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("sys install firefox --legacy --flatpak"), + "stderr must give legacy alternative: {stderr}" + ); +} + #[test] fn an_explicit_backend_never_falls_back_to_another_lane() { - // No Portage on this host, so an explicit `--portage` install must fail - // with an explanation and must not try Flatpak/snap/anything else. if effective_uid_is_root() { return; } @@ -191,7 +276,7 @@ fn an_explicit_backend_never_falls_back_to_another_lane() { .env("PATH", empty.path()) .arg("--root") .arg(root.path()) - .args(["install", "some-app", "--portage"]) + .args(["install", "some-app", "--legacy", "--portage"]) .output() .expect("run sys"); assert!(!out.status.success()); @@ -238,6 +323,34 @@ fn an_unqualified_install_without_a_model_offers_options_and_installs_nothing() .exists()); } +#[test] +fn please_install_enters_same_ai_workflow() { + if effective_uid_is_root() { + return; + } + let root = tempfile::tempdir().expect("temp root"); + let empty = tempfile::tempdir().expect("empty PATH"); + let out = sys() + .env("PATH", empty.path()) + .env("PHOEBUS_AI_PROVIDER", "none") + .env("PHOEBUS_AI_BACKEND", "direct") + .arg("--root") + .arg(root.path()) + .args(["please", "install", "firefox"]) + .output() + .expect("run sys"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("No connected model") || stderr.contains("no AI provider"), + "stderr: {stderr}" + ); + assert!( + stderr.contains("--flatpak") && stderr.contains("--portage"), + "the offer must name the explicit backends: {stderr}" + ); +} + #[test] fn the_help_lists_every_backend_flag() { let out = sys().arg("--help").output().expect("run sys"); @@ -250,6 +363,8 @@ fn the_help_lists_every_backend_flag() { "--snap", "--appimage", "--ebuild", + "--legacy", + "--broker", ] { assert!(stdout.contains(flag), "help is missing {flag}"); } @@ -257,14 +372,11 @@ fn the_help_lists_every_backend_flag() { #[test] fn choose_never_invents_a_candidate() { - // Depending on the host, a lane may or may not be resolvable. Either way the - // output must be a real selection with rejected alternatives, or a clear - // fail-closed error — never a fabricated package. let root = tempfile::tempdir().expect("temp root"); let out = sys() .arg("--root") .arg(root.path()) - .args(["choose", "some-package"]) + .args(["choose", "some-package", "--legacy"]) .output() .expect("run sys"); let stdout = String::from_utf8_lossy(&out.stdout); diff --git a/installer/live/build.sh b/installer/live/build.sh index 511235e..9d1bd0b 100755 --- a/installer/live/build.sh +++ b/installer/live/build.sh @@ -341,7 +341,7 @@ install -d -m 0700 "$rootfs/home/phoebus/.config/DankMaterialShell" # Quickshell frontend: the welcome window and the graphical installer, each a # self-contained config with the shared Common module materialised. if [[ -d "$here/desktop" ]]; then - for cfgname in phoebus-welcome phoebus-install; do + for cfgname in phoebus-welcome phoebus-install phoebus-assistant; do [[ -f "$here/desktop/$cfgname/shell.qml" ]] || { echo "live build: missing desktop config $cfgname" >&2; exit 1; } install -d -m 0755 "$rootfs/etc/xdg/quickshell/$cfgname" diff --git a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml new file mode 100644 index 0000000..4f396ac --- /dev/null +++ b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml @@ -0,0 +1,175 @@ +pragma Singleton +import QtQuick +import Quickshell +import Quickshell.Io + +// Typed JSON-RPC bridge to `sys --assistant-bridge`. +// Shares the exact same deterministic and AI admin broker with the CLI. +Singleton { + id: root + + property bool ready: false + property bool crashed: false + property string lastError: "" + property var handshake: null + + property var pending: ({}) + property int nextId: 1 + + signal event(string name, var data) + signal handshakeReady() + + readonly property var bridgeCommand: { + const override = Quickshell.env("PHOEBUS_ASSISTANT_BRIDGE_CMD"); + if (override && override.length > 0) + return override.split(" ").filter(part => part.length > 0); + return ["/usr/bin/sudo", "-n", "/usr/local/bin/sys", "--assistant-bridge"]; + } + + Timer { + interval: 400 + repeat: true + running: proc.running && root.handshake === null + onTriggered: root.refreshHandshake(null) + } + + function start() { + if (!proc.running) + proc.running = true; + } + + function stop() { + if (proc.running) + proc.running = false; + } + + function call(op, payload, onDone) { + const id = root.nextId++; + if (onDone) + root.pending[id] = onDone; + const request = Object.assign({ id: id, op: op }, payload || {}); + const line = JSON.stringify(request) + "\n"; + if (!proc.running) { + delete root.pending[id]; + root.lastError = "backend not running"; + if (onDone) + onDone({ ok: false, error: "The assistant broker is not running." }); + return; + } + proc.write(line); + } + + function handleLine(line) { + const text = ("" + line).trim(); + if (text.length === 0) + return; + let msg; + try { + msg = JSON.parse(text); + } catch (e) { + console.log("assistant-bridge: unparsable line: " + text); + return; + } + if (msg.id !== undefined && root.pending[msg.id]) { + const cb = root.pending[msg.id]; + delete root.pending[msg.id]; + cb(msg); + } + } + + function refreshHandshake(cb) { + call("handshake", {}, reply => { + if (reply.ok) { + root.handshake = reply.result; + root.handshakeReady(); + } + if (cb) + cb(reply); + }); + } + + function ask(query, backend, cb) { + call("ask", { request: query, backend: backend }, cb); + } + + function execute(actions, digest, yes, cb) { + call("execute", { actions: actions, digest: digest, yes: yes }, cb); + } + + function legacyInstall(application, backend, cb) { + call("legacy_install", { application: application, backend: backend }, cb); + } + + function legacyExecute(phrase, action, yes, cb) { + call("legacy_execute", { phrase: phrase, action: action, yes: yes }, cb); + } + + function getUpdates(cb) { + call("updates", {}, cb); + } + + function getProactiveAlerts(cb) { + call("proactive_alerts", {}, cb); + } + + function snoozeAlerts(durationSeconds, cb) { + call("proactive_snooze", { duration_seconds: durationSeconds }, cb); + } + + function dismissAlert(fingerprint, cb) { + call("proactive_dismiss", { fingerprint: fingerprint }, cb); + } + + function getPreferences(cb) { + call("get_preferences", {}, cb); + } + + function setPreferences(prefs, cb) { + call("set_preferences", { preferences: prefs }, cb); + } + + function getHistory(cb) { + call("history", {}, cb); + } + + function undo(snapshot, cb) { + call("undo", { snapshot: snapshot, yes: true }, cb); + } + + Process { + id: proc + command: root.bridgeCommand + stdinEnabled: true + running: false + + onStarted: { + root.ready = true; + root.crashed = false; + root.refreshHandshake(null); + } + + onExited: exitCode => { + root.ready = false; + root.crashed = true; + const ids = Object.keys(root.pending); + for (let i = 0; i < ids.length; i++) { + const cb = root.pending[ids[i]]; + delete root.pending[ids[i]]; + try { + cb({ ok: false, error: "The assistant bridge stopped (exit " + exitCode + ")." }); + } catch (e) {} + } + } + + stdout: SplitParser { + onRead: line => root.handleLine(line) + } + + stderr: SplitParser { + onRead: line => { + root.lastError = line; + console.log("assistant-bridge err: " + line); + } + } + } +} diff --git a/installer/live/desktop/phoebus-assistant/Common b/installer/live/desktop/phoebus-assistant/Common new file mode 120000 index 0000000..60d3b0a --- /dev/null +++ b/installer/live/desktop/phoebus-assistant/Common @@ -0,0 +1 @@ +../common \ No newline at end of file diff --git a/installer/live/desktop/phoebus-assistant/shell.qml b/installer/live/desktop/phoebus-assistant/shell.qml new file mode 100644 index 0000000..7ee79a3 --- /dev/null +++ b/installer/live/desktop/phoebus-assistant/shell.qml @@ -0,0 +1,708 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import "Common" + +ShellRoot { + id: shell + + property string currentTab: "assistant" // "assistant", "updates", "legacy", "alerts", "preferences" + property var conversation: [] + property bool busy: false + property string statusText: "Ready" + property var activeAlerts: [] + property var updateOverview: null + property var preferences: null + + Component.onCompleted: { + AssistantBridge.start(); + refreshStatus(); + } + + function refreshStatus() { + AssistantBridge.getProactiveAlerts(reply => { + if (reply.ok && reply.result) { + shell.activeAlerts = reply.result.alerts || []; + } + }); + AssistantBridge.getUpdates(reply => { + if (reply.ok && reply.result) { + shell.updateOverview = reply.result; + } + }); + AssistantBridge.getPreferences(reply => { + if (reply.ok && reply.result) { + shell.preferences = reply.result; + } + }); + } + + function addMessage(sender, text, data) { + const item = { + sender: sender, + text: text, + data: data || null, + time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + }; + const list = shell.conversation.slice(); + list.push(item); + shell.conversation = list; + } + + function submitPrompt(query) { + if (!query || query.trim().length === 0) + return; + const q = query.trim(); + addMessage("user", q, null); + shell.busy = true; + shell.statusText = "Investigating request..."; + + AssistantBridge.ask(q, null, reply => { + shell.busy = false; + if (!reply.ok) { + shell.statusText = "Error: " + reply.error; + addMessage("assistant", "Could not complete request: " + reply.error, null); + return; + } + shell.statusText = "Plan prepared"; + const res = reply.result; + if (res.kind === "install") { + addMessage("assistant", res.recommendation, res); + } else if (res.kind === "plan") { + addMessage("assistant", res.summary, res); + } else { + addMessage("assistant", "Completed.", res); + } + }); + } + + function executePlan(planData) { + shell.busy = true; + shell.statusText = "Executing approved plan..."; + const actions = planData.action ? [planData.action] : (planData.actions ? planData.actions.map(a => a.action || a) : []); + + AssistantBridge.execute(actions, planData.digest, true, reply => { + shell.busy = false; + if (!reply.ok) { + shell.statusText = "Execution failed"; + addMessage("assistant", "Execution failed: " + reply.error, null); + } else { + shell.statusText = "Installed successfully"; + addMessage("assistant", "Operation completed successfully.", { + completed: true, + application: planData.application, + snapshot: reply.result ? reply.result.snapshot : null + }); + refreshStatus(); + } + }); + } + + function launchApplication(app) { + if (!app) return; + Quickshell.execDetached(["gtk-launch", app]); + } + + FloatingWindow { + id: window + title: "Phoebus Assistant" + color: "transparent" + width: 820 + height: 640 + + Rectangle { + anchors.fill: parent + radius: 12 + color: Theme.background + border.color: Theme.border + border.width: 1 + + ColumnLayout { + anchors.fill: parent + anchors.margins: 16 + spacing: 12 + + // Header + RowLayout { + Layout.fillWidth: true + spacing: 12 + + Label { + text: "Phoebus Assistant" + color: Theme.text + font.pixelSize: 18 + font.bold: true + } + + Rectangle { + Layout.preferredWidth: 8 + Layout.preferredHeight: 8 + radius: 4 + color: AssistantBridge.ready ? Theme.primary : Theme.warning + } + + Label { + text: AssistantBridge.ready ? "Connected" : "Offline" + color: Theme.muted + font.pixelSize: 12 + } + + Item { Layout.fillWidth: true } + + // Tab buttons + RowLayout { + spacing: 4 + + PhoebusButton { + text: "Assistant" + primary: shell.currentTab === "assistant" + onClicked: shell.currentTab = "assistant" + } + + PhoebusButton { + text: "Updates" + (shell.updateOverview && shell.updateOverview.sources ? " (" + shell.updateOverview.sources.reduce((a, c) => a + c.updates.length, 0) + ")" : "") + primary: shell.currentTab === "updates" + onClicked: { + shell.currentTab = "updates"; + refreshStatus(); + } + } + + PhoebusButton { + text: "Legacy Admin" + primary: shell.currentTab === "legacy" + onClicked: shell.currentTab = "legacy" + } + + PhoebusButton { + text: "Alerts" + (shell.activeAlerts.length > 0 ? " (" + shell.activeAlerts.length + ")" : "") + primary: shell.currentTab === "alerts" + onClicked: { + shell.currentTab = "alerts"; + refreshStatus(); + } + } + + PhoebusButton { + text: "Preferences" + primary: shell.currentTab === "preferences" + onClicked: { + shell.currentTab = "preferences"; + refreshStatus(); + } + } + } + } + + Rectangle { + Layout.fillWidth: true + height: 1 + color: Theme.border + } + + // TAB 1: Conversational Assistant + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + visible: shell.currentTab === "assistant" + spacing: 10 + + ListView { + id: chatList + Layout.fillWidth: true + Layout.fillHeight: true + clip: true + spacing: 12 + model: shell.conversation + + delegate: Rectangle { + width: chatList.width + height: msgCol.height + 16 + radius: 8 + color: modelData.sender === "user" ? Theme.cardHover : Theme.card + border.color: Theme.border + border.width: 1 + + ColumnLayout { + id: msgCol + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + anchors.margins: 10 + spacing: 8 + + RowLayout { + Layout.fillWidth: true + Label { + text: modelData.sender === "user" ? "You" : "Phoebus Assistant" + color: modelData.sender === "user" ? Theme.primary : Theme.accent + font.bold: true + font.pixelSize: 13 + } + Item { Layout.fillWidth: true } + Label { + text: modelData.time + color: Theme.muted + font.pixelSize: 11 + } + } + + Label { + Layout.fillWidth: true + text: modelData.text + color: Theme.text + font.pixelSize: 14 + wrapMode: Text.Wrap + } + + // Recommendation / Action Card + ColumnLayout { + Layout.fillWidth: true + visible: modelData.data !== null + spacing: 8 + + // Action buttons for installation + RowLayout { + Layout.fillWidth: true + visible: modelData.data && modelData.data.kind === "install" && !modelData.data.completed + spacing: 8 + + PhoebusButton { + text: "Install" + primary: true + enabled: !shell.busy + onClicked: shell.executePlan(modelData.data) + } + + PhoebusButton { + id: detailsBtn + property bool expanded: false + text: expanded ? "Hide Details" : "Compare Options" + onClicked: expanded = !expanded + } + } + + // Expandable candidate details + ColumnLayout { + Layout.fillWidth: true + visible: detailsBtn && detailsBtn.expanded + spacing: 4 + + Label { + text: "Resolved Source: " + (modelData.data ? modelData.data.backend + " (" + modelData.data.source + ")" : "") + color: Theme.muted + font.pixelSize: 12 + } + Label { + text: "Plan Digest: " + (modelData.data ? modelData.data.digest : "") + color: Theme.muted + font.pixelSize: 11 + } + } + + // Completed follow-up action + RowLayout { + Layout.fillWidth: true + visible: modelData.data && modelData.data.completed && modelData.data.application + spacing: 8 + + PhoebusButton { + text: "Launch " + (modelData.data ? modelData.data.application : "App") + primary: true + onClicked: shell.launchApplication(modelData.data.application) + } + } + } + } + } + + onCountChanged: { + Qt.callLater(() => chatList.positionViewAtEnd()); + } + } + + // Prompt bar + RowLayout { + Layout.fillWidth: true + spacing: 8 + + TextField { + id: promptField + Layout.fillWidth: true + placeholderText: "Ask Phoebus... (e.g. Install Firefox, Show updates, Check audio)" + color: Theme.text + placeholderTextColor: Theme.muted + background: Rectangle { + radius: 8 + color: Theme.card + border.color: promptField.activeFocus ? Theme.primary : Theme.border + border.width: 1 + } + onAccepted: { + if (text.length > 0) { + shell.submitPrompt(text); + text = ""; + } + } + } + + PhoebusButton { + text: "Send" + primary: true + enabled: !shell.busy && promptField.text.trim().length > 0 + onClicked: { + shell.submitPrompt(promptField.text); + promptField.text = ""; + } + } + } + } + + // TAB 2: Multi-Source Updates + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + visible: shell.currentTab === "updates" + spacing: 12 + + Label { + text: "Unified Multi-Source Updates" + color: Theme.text + font.pixelSize: 16 + font.bold: true + } + + ListView { + Layout.fillWidth: true + Layout.fillHeight: true + clip: true + spacing: 8 + model: shell.updateOverview ? shell.updateOverview.sources : [] + + delegate: Rectangle { + width: parent.width + height: srcCol.height + 16 + radius: 8 + color: Theme.card + border.color: Theme.border + border.width: 1 + + ColumnLayout { + id: srcCol + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + anchors.margins: 10 + spacing: 6 + + RowLayout { + Layout.fillWidth: true + Label { + text: modelData.backend.toUpperCase() + color: Theme.primary + font.bold: true + } + Item { Layout.fillWidth: true } + Label { + text: modelData.updates.length + " update(s)" + color: Theme.muted + } + } + + Label { + text: modelData.note + color: Theme.muted + font.pixelSize: 12 + } + + Repeater { + model: modelData.updates + Label { + text: "• " + modelData.name + " (" + (modelData.current_version || "none") + " -> " + modelData.new_version + ")" + color: Theme.text + font.pixelSize: 12 + } + } + } + } + } + + RowLayout { + Layout.fillWidth: true + PhoebusButton { + text: "Refresh Updates" + onClicked: refreshStatus() + } + PhoebusButton { + text: "Apply All Updates" + primary: true + onClicked: shell.submitPrompt("update system") + } + } + } + + // TAB 3: Legacy Admin + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + visible: shell.currentTab === "legacy" + spacing: 12 + + Label { + text: "Deterministic Legacy Administration (No Model)" + color: Theme.text + font.pixelSize: 16 + font.bold: true + } + + RowLayout { + Layout.fillWidth: true + spacing: 8 + + Label { text: "Lane:"; color: Theme.muted } + + ComboBox { + id: legacyLaneCombo + model: ["flatpak", "portage", "nix", "snap", "appimage", "ebuild"] + } + + TextField { + id: legacyAppField + Layout.fillWidth: true + placeholderText: "Application name (e.g. firefox, vim)" + color: Theme.text + placeholderTextColor: Theme.muted + background: Rectangle { + radius: 6 + color: Theme.card + border.color: Theme.border + border.width: 1 + } + } + + PhoebusButton { + text: "Install Explicitly" + primary: true + enabled: legacyAppField.text.trim().length > 0 + onClicked: { + const app = legacyAppField.text.trim(); + const lane = legacyLaneCombo.currentText; + shell.statusText = "Resolving legacy install..."; + AssistantBridge.legacyInstall(app, lane, reply => { + if (reply.ok) { + shell.executePlan(reply.result); + } else { + shell.statusText = "Error: " + reply.error; + } + }); + } + } + } + + RowLayout { + Layout.fillWidth: true + spacing: 8 + + TextField { + id: legacyPhraseField + Layout.fillWidth: true + placeholderText: "Deterministic action (e.g. enable sshd, history, undo)" + color: Theme.text + placeholderTextColor: Theme.muted + background: Rectangle { + radius: 6 + color: Theme.card + border.color: Theme.border + border.width: 1 + } + } + + PhoebusButton { + text: "Execute Command" + enabled: legacyPhraseField.text.trim().length > 0 + onClicked: { + const p = legacyPhraseField.text.trim(); + AssistantBridge.legacyExecute(p, null, true, reply => { + if (reply.ok) { + shell.statusText = "Executed successfully"; + addMessage("assistant", "Executed: " + p + "\n" + (reply.result ? reply.result.output : ""), null); + shell.currentTab = "assistant"; + } else { + shell.statusText = "Error: " + reply.error; + } + }); + } + } + } + + Item { Layout.fillHeight: true } + } + + // TAB 4: Proactive Alerts + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + visible: shell.currentTab === "alerts" + spacing: 12 + + Label { + text: "Quiet Proactive System Alerts" + color: Theme.text + font.pixelSize: 16 + font.bold: true + } + + ListView { + Layout.fillWidth: true + Layout.fillHeight: true + clip: true + spacing: 8 + model: shell.activeAlerts + + delegate: Rectangle { + width: parent.width + height: alertCol.height + 16 + radius: 8 + color: Theme.card + border.color: modelData.severity === "warning" ? Theme.warning : Theme.border + border.width: 1 + + ColumnLayout { + id: alertCol + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + anchors.margins: 10 + spacing: 6 + + RowLayout { + Layout.fillWidth: true + Label { + text: modelData.title + color: modelData.severity === "warning" ? Theme.warning : Theme.text + font.bold: true + font.pixelSize: 14 + } + Item { Layout.fillWidth: true } + Label { + text: modelData.category + color: Theme.muted + font.pixelSize: 11 + } + } + + Label { + Layout.fillWidth: true + text: modelData.message + color: Theme.text + wrapMode: Text.Wrap + font.pixelSize: 13 + } + + RowLayout { + Layout.fillWidth: true + spacing: 8 + + PhoebusButton { + text: "Act: " + (modelData.suggested_phrase || "Fix") + primary: true + visible: modelData.suggested_phrase !== null + onClicked: { + shell.submitPrompt(modelData.suggested_phrase); + shell.currentTab = "assistant"; + } + } + + PhoebusButton { + text: "Snooze 1h" + onClicked: { + AssistantBridge.snoozeAlerts(3600, () => refreshStatus()); + } + } + + PhoebusButton { + text: "Dismiss" + onClicked: { + AssistantBridge.dismissAlert(modelData.fingerprint, () => refreshStatus()); + } + } + } + } + } + } + + Label { + visible: shell.activeAlerts.length === 0 + text: "No active proactive alerts. System is quiet and running normally." + color: Theme.muted + font.italic: true + } + } + + // TAB 5: Preferences + ColumnLayout { + Layout.fillWidth: true + Layout.fillHeight: true + visible: shell.currentTab === "preferences" + spacing: 12 + + Label { + text: "Administration Preferences" + color: Theme.text + font.pixelSize: 16 + font.bold: true + } + + RowLayout { + spacing: 12 + Label { text: "Profile Strategy:"; color: Theme.muted } + ComboBox { + id: profileCombo + model: ["Balanced", "FastInstallation", "NativeIntegration", "ApplicationIsolation"] + currentIndex: 0 + } + } + + PhoebusButton { + text: "Save Preferences" + primary: true + onClicked: { + if (shell.preferences) { + shell.preferences.profile = profileCombo.currentText; + AssistantBridge.setPreferences(shell.preferences, reply => { + if (reply.ok) shell.statusText = "Preferences saved."; + }); + } + } + } + + Item { Layout.fillHeight: true } + } + + // Footer status bar + Rectangle { + Layout.fillWidth: true + height: 1 + color: Theme.border + } + + RowLayout { + Layout.fillWidth: true + Label { + text: shell.statusText + color: Theme.muted + font.pixelSize: 12 + } + Item { Layout.fillWidth: true } + Label { + text: "Phoebus OS • sys 0.1.0" + color: Theme.muted + font.pixelSize: 11 + } + } + } + } + } +} diff --git a/installer/tests/vm/sys-acceptance.sh b/installer/tests/vm/sys-acceptance.sh index 958ddba..bc53992 100755 --- a/installer/tests/vm/sys-acceptance.sh +++ b/installer/tests/vm/sys-acceptance.sh @@ -49,7 +49,7 @@ run_expect_nonzero() { # json_nonzero json_nonzero() { local id="$1" needle="$2" json="$3" - "$SYS" --action "$json" >"$WORK/$id.out" 2>"$WORK/$id.err" + "$SYS" --legacy --action "$json" >"$WORK/$id.out" 2>"$WORK/$id.err" local rc=$? if [[ $rc -ne 0 ]] && grep -qi -- "$needle" "$WORK/$id.err" "$WORK/$id.out"; then report "$id" PASS "rejected: $(head -c 160 "$WORK/$id.err" | tr '\n' ' ')" @@ -64,33 +64,40 @@ echo "sys-acceptance: SYS=$SYS MUTATE=$MUTATE" # --- Read-only deterministic and JSON paths ------------------------------- run_expect_zero identity --version -run_expect_zero history history -run_expect_zero appimage-empty --root / appimage list -run_expect_zero ebuild-empty --root / ebuilds +run_expect_zero history-legacy history --legacy +if [[ "$(id -u)" -eq 0 ]]; then + run_expect_zero undo-legacy undo --legacy +else + run_expect_nonzero nonroot-undo "mutating actions require root" undo --legacy +fi +run_expect_zero appimage-empty --root / --legacy appimage list +run_expect_zero ebuild-empty --root / --legacy ebuilds # --- Failure cases --------------------------------------------------------- -run_expect_nonzero invalid-natural "could not parse" -- install --color=n -run_expect_nonzero unknown-phrase "unsupported instruction" frobnicate +run_expect_nonzero invalid-natural "could not parse" --legacy -- install --color=n +run_expect_nonzero unknown-phrase "unsupported instruction" --legacy frobnicate +run_expect_nonzero action-without-legacy-or-broker "require --legacy" --action '{"action":"history"}' +run_expect_nonzero install-legacy-nosource "requires an explicit package source flag" install firefox --legacy json_nonzero unknown-action "invalid action" '{"action":"run_shell","command":"rm -rf /"}' json_nonzero unknown-field "invalid action" '{"action":"history","x":1}' -json_nonzero option-operand "invalid action" '{"action":"install_package","atom":"-C"}' +json_nonzero option-operand "invalid" '{"action":"install_package","atom":"-C"}' json_nonzero bad-snap-name "invalid" '{"action":"snap_install","name":"Bad Name"}' json_nonzero bad-appimage-hash "SHA-256" '{"action":"appimage_acquire","name":"x","url":"https://e/x","sha256":"00"}' json_nonzero ebuild-traversal "invalid" '{"action":"custom_ebuild_prepare","atom":"../../x","version":"1","rationale":"r","ebuild":"EAPI=8"}' # --- Offline / model-free behaviour --------------------------------------- if [[ "$(id -u)" -ne 0 ]]; then - run_expect_nonzero nonroot-mutation "root" --action '{"action":"set_package_preference","name":"firefox","backend":"flatpak"}' + run_expect_nonzero nonroot-mutation "root" --legacy --action '{"action":"set_package_preference","name":"firefox","backend":"flatpak"}' fi # With no provider, `ask` must fall back deterministically and exit nonzero. -PHOEBUS_AI_PROVIDER= PHOEBUS_AI_BACKEND=direct \ +PHOEBUS_AI_PROVIDER="" PHOEBUS_AI_BACKEND=direct \ run_expect_nonzero ask-offline "no AI provider" ask "install vim" # --- Choosing a source (never invents a candidate) ------------------------ -"$SYS" --root / choose unused-package-xyz >"$WORK/choose.out" 2>"$WORK/choose.err" +"$SYS" --root / choose unused-package-xyz --legacy >"$WORK/choose.out" 2>"$WORK/choose.err" if grep -q "Selected package:" "$WORK/choose.out"; then report choose PASS "selection: $(grep -m1 'Selected package:' "$WORK/choose.out")" -elif grep -qi "no compatible\|no AI provider" "$WORK/choose.err"; then +elif grep -qi "no compatible\|no AI provider\|no real candidate" "$WORK/choose.err"; then report choose PASS "no candidate: $(head -c 160 "$WORK/choose.err" | tr '\n' ' ')" else report choose FAIL "unexpected output: $(head -c 200 "$WORK/choose.err")" @@ -98,16 +105,16 @@ fi # --- AI-first installation workflow (read-only cases) --------------------- # Conflicting backend flags must be rejected by the CLI. -"$SYS" install firefox --flatpak --nix >"$WORK/conflict.out" 2>"$WORK/conflict.err" -if [[ $? -ne 0 ]] && grep -qi "cannot be used with\|conflict\|not allowed" "$WORK/conflict.err"; then +if ! "$SYS" install firefox --flatpak --nix >"$WORK/conflict.out" 2>"$WORK/conflict.err" && \ + grep -qi "cannot be used with\|conflict\|not allowed" "$WORK/conflict.err"; then report install-flag-conflict PASS "rejected" else report install-flag-conflict FAIL "$(head -c 160 "$WORK/conflict.err")" fi # A backend flag without an install is refused. -"$SYS" --flatpak history >"$WORK/flag.out" 2>"$WORK/flag.err" -if [[ $? -ne 0 ]] && grep -q "only apply to" "$WORK/flag.err"; then +if ! "$SYS" --flatpak history --legacy >"$WORK/flag.out" 2>"$WORK/flag.err" && \ + grep -q "only apply to" "$WORK/flag.err"; then report install-flag-alone PASS "refused" else report install-flag-alone FAIL "$(head -c 160 "$WORK/flag.err")" @@ -115,16 +122,16 @@ fi # An unqualified install with no provider must offer the explicit commands and # install nothing. -PHOEBUS_AI_PROVIDER= PHOEBUS_AI_BACKEND=direct \ - "$SYS" install unused-package-xyz >"$WORK/noai.out" 2>"$WORK/noai.err" -if [[ $? -ne 0 ]] && grep -q -- "--flatpak" "$WORK/noai.err"; then +if ! PHOEBUS_AI_PROVIDER="" PHOEBUS_AI_BACKEND=direct \ + "$SYS" install unused-package-xyz >"$WORK/noai.out" 2>"$WORK/noai.err" && \ + grep -q -- "--flatpak" "$WORK/noai.err"; then report install-no-model-offer PASS "no model: deterministic offer shown" else report install-no-model-offer FAIL "$(head -c 200 "$WORK/noai.err")" fi # Read-only investigation returns structured evidence. -"$SYS" --action '{"action":"check_backend","backend":"flatpak"}' >"$WORK/be.out" 2>"$WORK/be.err" +"$SYS" --legacy --action '{"action":"check_backend","backend":"flatpak"}' >"$WORK/be.out" 2>"$WORK/be.err" if grep -q '"backend"' "$WORK/be.out"; then report investigate-check-backend PASS "$(head -c 120 "$WORK/be.out" | tr '\n' ' ')" else @@ -134,7 +141,7 @@ fi # --- Optional mutating group (disposable VM only) ------------------------- if [[ "$MUTATE" == "1" ]]; then PKG="${SYS_ACCEPTANCE_PACKAGE:-app-misc/hello}" - if "$SYS" -y install "$PKG" >"$WORK/install.out" 2>&1; then + if "$SYS" -y install "$PKG" --legacy --portage >"$WORK/install.out" 2>&1; then if emerge --pretend --quiet "$PKG" >/dev/null 2>&1; then report mutate-install PASS "installed $PKG" else @@ -143,12 +150,12 @@ if [[ "$MUTATE" == "1" ]]; then else report mutate-install FAIL "sys install failed: $(head -c 160 "$WORK/install.out")" fi - if "$SYS" -y remove "$PKG" >"$WORK/remove.out" 2>&1; then + if "$SYS" -y remove "$PKG" --legacy >"$WORK/remove.out" 2>&1; then report mutate-remove PASS "removed $PKG" else report mutate-remove FAIL "sys remove failed: $(head -c 160 "$WORK/remove.out")" fi - "$SYS" history >"$WORK/hist.out" 2>&1 + "$SYS" history --legacy >"$WORK/hist.out" 2>&1 if grep -q "$PKG" "$WORK/hist.out"; then report mutate-history PASS "transaction recorded" else